/**
 * 运费快速计算系统 - 整合版本
 * 解决模块化架构中的API初始化问题，统一使用POST请求
 * @author 运费系统团队
 */

const FreightApp = {
    setup() {
        const { createApp, ref, reactive, onMounted, computed, watch, nextTick } = Vue;
        // 基础配置
        const API_BASE_URL = '/freight';

        // 获取计费模式名称
        const getPricingModelName = (pricingModel) => {
            return pricingModel === 1 ? '首重续重' : '首重续重+重量区间';
        };

        // 响应式数据
        const activeTab = ref('calculate');
        const calculating = ref(false);
        const submitting = ref(false);
        const error = ref('');
        const successMsg = ref('');
        const freightResult = ref(null);
        const showFormulaDetails = ref(true); // 新增：控制计算公式展开/折叠状态

        // 表单数据
        const freightForm = reactive({
            weight: null, length: null, width: null, height: null,
            fromAreaId: '', toAreaId: '',
            toProvinceName: '', // 新增：目标省份名称
            toCityName: '', // 新增：目标城市名称
            toDistrictName: '', // 新增：目标区县名称
            strategyId: '', warehouseCode: '', logisticsCompanyCode: ''
        });

        const strategyForm = reactive({
            id: null, name: '', description: '', pricingModel: '',
            firstWeightKg: null, firstWeightFee: null,
            additionalWeightKg: null, additionalWeightFee: null,
            volumetricWeightRatio: null, status: 1
        });

        const areaForm = reactive({
            areaId: null, provinceCode: '', provinceName: '', provinceShortName: '',
            cityCode: '', cityName: '', cityShortName: '',
            districtCode: '', districtName: '', districtShortName: '', level: ''
        });

        const mappingForm = reactive({
            strategyId: '', areaId: '', segmentRuleIds: []
        });

        const batchMappingForm = reactive({
            strategyId: '', areaIds: [], segmentRuleIds: []
        });

        const editMappingForm = reactive({
            strategyId: '', ruleId: '', upperBound: '', freight: '', originalAreas: [], selectedAreaIds: []
        });

        const weightRuleForm = reactive({
            id: null, strategyId: '', strategyName: '', upperBound: null, freight: null
        });

        const assignmentForm = reactive({
            warehouseCode: '', logisticsCompanyCode: '', strategyId: '', status: 1
        });

        const batchAssignmentForm = reactive({
            warehouseCodesText: '', logisticsCompanyCodesText: '', strategyId: '', status: 1
        });

        // 数据存储
        const areas = ref([]);
        const strategies = ref([]);
        const mappings = ref([]);
        const weightRules = ref([]);
        const assignments = ref([]);
        const batchWeightRules = ref([]);
        const filteredAssignments = ref([]);
        const mappingMergedData = ref([]);
        const mappingGroupByAreaData = ref([]); // 新增：按区域分组数据
        const filteredWeightRules = ref([]);

        // 显示模式状态
        const displayMode = ref('by-rule'); // 'by-rule' 或 'by-area'
        // 模态框控制
        const showAddStrategyModal = ref(false);
        const showEditStrategyModal = ref(false);
        const showCopyStrategyModal = ref(false);
        const currentStrategyForCopy = ref(null);
        const copyStrategyForm = reactive({
            id: null,
            newName: '',
            description: ''
        });
        const copyStrategyNewName = ref('');
        const copyStrategyDescription = ref('');
        const showAddAreaModal = ref(false);
        const showEditAreaModal = ref(false);
        const showAddMappingModal = ref(false);
        const showEditMappingModal = ref(false);
        const showBatchMappingModal = ref(false);
        const showAddWeightRuleModal = ref(false);
        const showEditWeightRuleModal = ref(false);
        const showAddAssignmentModal = ref(false);
        const showBatchAssignmentModal = ref(false);

        // 策略编辑相关状态（用于映射管理页面）
        const showMappingStrategyEditModal = ref(false);
        const submittingMappingStrategy = ref(false);
        const mappingStrategyForm = reactive({
            id: null,
            name: '',
            description: '',
            pricingModel: '',
            firstWeightKg: null,
            firstWeightFee: null,
            additionalWeightKg: null,
            additionalWeightFee: null,
            volumetricWeightRatio: null,
            status: 1,
            weightRules: [], // 新增：重量规则数组
            selectedAreas: [] // 新增：选中的运送区域
        });

        // 策略编辑的区域选择器状态
        const showMappingAreaSelector = ref(false);
        const mappingAreaState = reactive({
            selectedProvinces: new Set(),
            selectedCities: new Set(),
            selectedDistricts: new Set(),
            expandedProvinces: new Set(),
            expandedCities: new Set()
        });

        // 其他状态
        const selectedStrategyId = ref('');
        const selectedMappingStrategyId = ref('');
        const selectedAssignment = ref(null);
        const selectedAssignmentIds = ref([]);
        const forceUpdateFlag = ref(0);

        // 策略区域配置页面状态
        const selectedAreaConfigStrategyId = ref('');
        const selectedAreaConfigAreaId = ref('');
        const selectedAreaDetail = ref(null);
        const strategyAreaDetails = ref([]);
        const isEditingAreaConfig = ref(false);
        const savingAreaConfig = ref(false);
        const currentWeightSegmentRules = ref([]);
        const showAddWeightSegmentModal = ref(false);
        const showEditWeightSegmentModal = ref(false);

        // 区域配置表单
        const areaConfigForm = reactive({
            strategyId: '',
            areaId: '',
            areaName: '',
            firstWeightKg: '',
            firstWeightFee: '',
            additionalWeightKg: '',
            additionalWeightFee: '',
            volumetricWeightRatio: '',
            status: 1,
            weightSegmentRules: []
        });

        // 重量区间规则表单
        const weightSegmentForm = reactive({
            id: null,
            upperBound: '',
            freight: ''
        });

        // 查询条件对象
        const strategyQuery = reactive({
            name: '',
            pricingModel: '',
            status: ''
        });

        const assignmentQuery = reactive({
            strategyId: '',
            warehouseCode: '',
            logisticsCompanyCode: '',
            status: ''
        });

        const areaQuery = reactive({
            level: '',
            provinceName: '',
            cityName: '',
            districtName: ''
        });

        const mappingQuery = reactive({
            areaName: ''
        });

        // 分页相关状态
        const areaPagination = reactive({
            currentPage: 1,
            pageSize: 10,
            totalItems: 0,
            totalPages: 0
        });

        // V3策略配置相关状态
        const showV3StrategyEditModal = ref(false);
        const showV3AreaSelector = ref(false);
        const submittingV3Strategy = ref(false);

        // V3策略编辑表单
        const v3StrategyEditForm = reactive({
            id: null,
            name: '',
            description: '',
            pricingModel: '',
            weightRules: [],
            selectedAreas: []
        });

        // V3区域选择器状态
        const v3AreaState = reactive({
            selectedProvinces: new Set(),
            selectedCities: new Set(),
            selectedDistricts: new Set(),
            expandedProvinces: new Set(),
            expandedCities: new Set()
        });

        // V3区域标签缓存（响应式数据）
        const v3SelectedAreaTags = ref([]);

        // 监听区域选择变化，异步更新标签
        const updateV3AreaTags = async () => {
            try {
                const tags = await window.vueAppInstance.getV3SelectedAreaTags();
                v3SelectedAreaTags.value = tags;
            } catch (error) {
                console.error('更新V3区域标签失败:', error);
                v3SelectedAreaTags.value = [];
            }
        };

        // V3计费规则编辑相关状态
        const showV3PricingRulesModal = ref(false);
        const submittingV3PricingRules = ref(false);
        const v3PricingRulesForm = reactive({
            strategyId: null,
            pricingId: null, // 如果是编辑已有配置
            name: '',
            description: '',
            firstWeightKg: 1.0,
            firstWeightFee: 0,
            additionalWeightKg: 1.0,
            additionalWeightFee: 0,
            volumetricWeightRatio: 0,
            status: 1,
            weightRules: [] // 重量区间规则
        });

        // V3当前选中的策略信息（用于计费规则编辑）
        const v3CurrentStrategy = ref(null);

        // V3地区选择完成后的回调函数
        const v3AreaSelectionCallback = ref(null);

        // 策略搜索相关
        const strategySearchKeyword = ref('');
        const showStrategyDropdown = ref(false);
        const filteredStrategies = ref([]);

        // 重量规则页面独立的策略搜索状态
        const weightRulesSearchKeyword = ref('');
        const showWeightRulesStrategyDropdown = ref(false);
        const filteredWeightRulesStrategies = ref([]);

        // 区域选择器相关
        const showAreaSelector = ref(false);
        const selectedProvince = ref(null);
        const selectedCity = ref(null);
        const selectedDistrict = ref(null);
        const areaTree = ref([]);

        // 级联选择器状态
        const cascaderState = reactive({
            selectedProvinces: new Set(),
            selectedCities: new Set(),
            selectedDistricts: new Set(),
            expandedProvinces: new Set(),
            expandedCities: new Set(),
            // 联动功能状态
            isLinkageEnabled: true // 默认启用联动功能
        });

        // API 调用方法 - 使用POST请求统一处理
        const api = {
            async request(method, url, data = null) {
                try {
                    console.log(`🔍 API请求: ${method} ${url}`, data);

                    // 检查axios是否可用
                    if (typeof axios === 'undefined') {
                        throw new Error('axios库未加载，请检查网络连接');
                    }

                    const config = {
                        method,
                        url: `${API_BASE_URL}${url}`,
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8',
                            'Accept': 'application/json;charset=UTF-8'
                        },
                        timeout: 10000
                    };

                    if (data) {
                        config.data = data;
                    }

                    const response = await axios(config);
                    console.log(`✅ API响应: ${method} ${url}`, response.data);
                    return response.data;
                } catch (err) {
                    console.error(`❌ API请求失败: ${method} ${url}`, err);
                    const errorMsg = err.response?.data?.msg || err.message || '网络请求失败';
                    throw new Error(errorMsg);
                }
            },

            // 基础HTTP方法
            get(url) { return this.request('GET', url); },
            post(url, data) { return this.request('POST', url, data); },

            // 具体业务API方法 - 全部使用POST请求，修复路径匹配问题
            calculateFreight: (data) => api.post('/freight/calculate', data),
            getStrategies: (query = {}) => api.post('/strategy/list', query),
            addStrategy: (data) => api.post('/strategy/add', data),
            updateStrategy: (data) => api.post('/strategy/edit', data),
            deleteStrategy: (strategyId) => api.post('/strategy/delete', { id: strategyId }),
            // 区域相关接口 - 分离公共接口和分页接口
            getAreas: (query = {}) => api.post('/area/list', query), // 公共接口，用于下拉框等
            getAreasWithPage: (query = {}) => api.post('/area/list-page', query), // 分页接口，专用于区域管理页面
            addArea: (data) => api.post('/area/add', data),
            updateArea: (data) => api.post('/area/update', data),
            deleteArea: (data) => api.post('/area/delete', data),
            exportAreas: (query = {}) => api.post('/area/export', query, { responseType: 'blob' }),
            getMappings: (query = {}) => api.post('/api/pricing-area-mapping/list', query),
            getMappingsMerged: (query = {}) => api.post('/api/pricing-area-mapping/merged-list', query),
            getMappingsGroupByArea: (query = {}) => api.post('/api/pricing-area-mapping/group-by-area-list', query),
            addMapping: (data) => api.post('/api/pricing-area-mapping/add', data),
            addBatchMappings: (data) => api.post('/api/pricing-area-mapping/batch-add', data),
            deleteMapping: (data) => api.post('/api/pricing-area-mapping/delete', data),
            batchDeleteMappings: (mappingIds) => api.post('/api/pricing-area-mapping/batch-delete', { mappingIds }),
            getWeightRules: (strategyId) => api.post('/weight-segment-rule/list', { strategyId }),
            addWeightRule: (data) => api.post('/weight-segment-rule/add', data),
            updateWeightRule: (data) => api.post('/weight-segment-rule/update', data),
            deleteWeightRule: (data) => api.post('/weight-segment-rule/delete', data),
            getAssignments: (query = {}) => api.post('/strategy-assignment/list', query),
            addAssignment: (data) => api.post('/strategy-assignment/assign', data),
            batchAssign: (data) => api.post('/strategy-assignment/batch-assign', data),
            deleteAssignment: (assignmentId) => api.post('/strategy-assignment/delete', { id: assignmentId }),
            batchDeleteAssignments: (assignmentIds) => api.post('/strategy-assignment/batch-delete', { ids: assignmentIds }),
            updateAssignmentStatus: (data) => api.post('/strategy-assignment/update-status', data),

            // 复制策略数据
            copyStrategyData: (copyData) => api.post('/strategy/copy-data', copyData)
        };

        // 工具方法
        const clearMessages = () => {
            error.value = '';
            successMsg.value = '';
        };

        const showMessage = (message, isError = false) => {
            clearMessages();
            if (isError) {
                error.value = message;
                console.error('❌ 操作失败:', message);
            } else {
                successMsg.value = message;
                console.log('✅ 操作成功:', message);
            }
            setTimeout(clearMessages, 3000);
        };

        const formatAreaName = (area) => {
            if (!area) return '未知区域';
            let name = area.provinceName || '';
            if (area.cityName && area.cityName !== area.provinceName) {
                name += '-' + area.cityName;
            }
            if (area.districtName && area.districtName !== area.cityName) {
                name += '-' + area.districtName;
            }
            return name || '未知区域';
        };

        const formatDate = (dateString) => {
            if (!dateString) return '-';
            return new Date(dateString).toLocaleString('zh-CN');
        };

        const getStrategyName = (strategyId) => {
            const currentStrategies = strategies.value || [];
            const strategy = currentStrategies.find(s => s.id === strategyId);
            return strategy ? strategy.name : '未知策略';
        };

        const getAreaName = (areaId) => {
            const currentAreas = areas.value || [];
            const area = currentAreas.find(a => a.id === areaId);
            return area ? formatAreaName(area) : '未知区域';
        };

        // 从区域树中查找地区名称（用于前端重复性检查）
        const findAreaNameById = (areaId) => {
            const searchInTree = (tree) => {
                for (const province of tree) {
                    // 检查省级
                    if (province.id === areaId) {
                        return province.name || '未知省份';
                    }

                    // 检查市级
                    if (province.children) {
                        for (const city of province.children) {
                            if (city.id === areaId) {
                                return `${province.name}-${city.name}`;
                            }

                            // 检查区县级
                            if (city.children) {
                                for (const district of city.children) {
                                    if (district.id === areaId) {
                                        return `${province.name}-${city.name}-${district.name}`;
                                    }
                                }
                            }
                        }
                    }
                }
                return null;
            };

            try {
                const tree = areaTree.value || [];
                const areaName = searchInTree(tree);
                return areaName || `地区ID:${areaId}`;
            } catch (error) {
                console.warn('查找地区名称失败:', error);
                return `地区ID:${areaId}`;
            }
        };

        // 运费计算功能
        const calculateFreight = async () => {
            console.log('开始运费计算，表单数据:', {
                weight: freightForm.weight,
                toAreaId: freightForm.toAreaId,
                strategyId: freightForm.strategyId,
                length: freightForm.length,
                width: freightForm.width,
                height: freightForm.height
            });

            // 进行详细的表单验证
            const missingFields = [];

            if (!freightForm.weight || freightForm.weight < 0) {
                missingFields.push('货物重量');
            }

            if (!freightForm.toAreaId) {
                missingFields.push('目标区域');
            }

            if (missingFields.length > 0) {
                const errorMsg = `请填写以下必要信息：${missingFields.join('、')}`;
                console.log('表单验证失败:', errorMsg);
                showMessage(errorMsg, true);
                return;
            }

            calculating.value = true;
            clearMessages();
            freightResult.value = null;

            try {
                console.log('发送运费计算请求...');
                const result = await api.calculateFreight(freightForm);
                console.log('运费计算响应:', result);

                if (result.code === 0) {
                    // 生成详细的计算公式
                    const detailedFormula = generateDetailedFormula(result.data, freightForm);

                    freightResult.value = {
                        ...result.data,
                        detailedFormula: detailedFormula
                    };
                    showMessage('运费计算成功');
                } else {
                    showMessage(result.msg || '计算失败', true);
                }
            } catch (err) {
                showMessage(err.message, true);
            } finally {
                calculating.value = false;
            }
        };

        /**
         * 生成详细的计算公式
         * @param {Object} result - API返回的计算结果
         * @param {Object} form - 用户输入的表单数据
         * @returns {String} 详细的计算公式文本
         */
        const generateDetailedFormula = (result, form) => {
            let formula = '';

            // 第一步：体积重计算（包含体积计算和抛重比说明）
            formula += '=== 第一步：体积重计算 ===\n\n';

            if (form.length && form.width && form.height) {
                const volume = form.length * form.width * form.height;
                const volumetricWeightRatio = result.volumetricWeightRatio || 0; // 抛重比
                const volumetricWeight = volume / volumetricWeightRatio;

                formula += `1. 体积计算：\n`;
                formula += `   体积 = 长度 × 宽度 × 高度\n`;
                formula += `   体积 = ${form.length}cm × ${form.width}cm × ${form.height}cm = ${volume.toLocaleString()}cm³\n\n`;

                formula += `2. 体积重计算（抛重比 1:${volumetricWeightRatio.toLocaleString()}）：\n`;
                formula += `   体积重 = 体积 ÷ 抛重比\n`;
                formula += `   体积重 = ${volume.toLocaleString()}cm³ ÷ ${volumetricWeightRatio.toLocaleString()} = ${volumetricWeight.toFixed(2)}kg\n\n`;

                formula += `   抛重比说明：1立方厘米 = 1/${volumetricWeightRatio.toLocaleString()}公斤\n`;
                formula += `   这是物流行业标准，用于将体积转换为等效重量\n\n`;
            } else {
                formula += `1. 未提供尺寸信息，仅按实际重量计费\n\n`;
            }

            // 第二步：计费重量确定（显示实重vs体积重的比较逻辑）
            formula += '=== 第二步：计费重量确定 ===\n\n';

            const actualWeight = form.weight || result.actualWeight || 0;
            const volumetricWeight = result.volumetricWeight || 0;
            const chargeableWeight = result.chargeableWeight || actualWeight;

            formula += `1. 实际重量：${actualWeight}kg\n`;

            if (volumetricWeight > 0) {
                formula += `2. 体积重：${volumetricWeight}kg\n\n`;
                formula += `3. 计费重量确定逻辑：\n`;
                formula += `   计费重量 = MAX(实际重量, 体积重)\n`;
                formula += `   计费重量 = MAX(${actualWeight}kg, ${volumetricWeight}kg) = ${chargeableWeight}kg\n\n`;

                if (chargeableWeight === actualWeight) {
                    formula += `   结果：按实际重量计费（实重 > 体积重）\n\n`;
                } else {
                    formula += `   结果：按体积重计费（体积重 > 实重）\n\n`;
                }
            } else {
                formula += `2. 未计算体积重，直接使用实际重量\n`;
                formula += `   计费重量 = ${chargeableWeight}kg\n\n`;
            }

            // 第三步：运费计算（显示具体的计费模式和计算公式）
            formula += '=== 第三步：运费计算 ===\n\n';

            // 获取策略信息
            const strategyName = result.strategyName || '未知策略';
            formula += `使用策略：${strategyName}\n\n`;

            // 判断计费模式
            if (result.usedWeightSegment) {
                formula += `计费模式：重量区间规则\n\n`;

                if (result.weightSegmentInfo) {
                    const segment = result.weightSegmentInfo;
                    formula += `适用区间：${segment.lowerBound || 0}kg - ${segment.upperBound}kg\n`;
                    formula += `区间费率：¥${segment.freight}/kg\n\n`;
                    formula += `计算公式：\n`;
                    formula += `运费 = 计费重量 × 区间费率\n`;
                    formula += `运费 = ${chargeableWeight}kg × ¥${segment.freight}/kg = ¥${result.freight}\n\n`;
                } else {
                    formula += `计算公式：按重量区间计费\n`;
                    formula += `运费 = ¥${result.freight}\n\n`;
                }
            } else {
                formula += `计费模式：首重续重\n\n`;

                const firstWeightKg = result.firstWeightKg || 1;
                const firstWeightFee = result.firstWeightFee || 0;
                const additionalWeightKg = result.additionalWeightKg || 1;
                const additionalWeightFee = result.additionalWeightFee || 0;

                formula += `首重设置：${firstWeightKg}kg 内 = ¥${firstWeightFee}\n`;
                formula += `续重设置：每 ${additionalWeightKg}kg 或不足 = ¥${additionalWeightFee}\n\n`;

                if (chargeableWeight <= firstWeightKg) {
                    formula += `计算过程：\n`;
                    formula += `计费重量(${chargeableWeight}kg) ≤ 首重(${firstWeightKg}kg)\n`;
                    formula += `运费 = 首重费用 = ¥${firstWeightFee}\n\n`;
                } else {
                    const additionalWeight = chargeableWeight - firstWeightKg;
                    const additionalUnits = Math.ceil(additionalWeight / additionalWeightKg);
                    const additionalFee = additionalUnits * additionalWeightFee;

                    formula += `计算过程：\n`;
                    formula += `1. 首重费用：¥${firstWeightFee}\n`;
                    formula += `2. 续重重量：${chargeableWeight}kg - ${firstWeightKg}kg = ${additionalWeight}kg\n`;
                    formula += `3. 续重计费单位：向上取整(${additionalWeight}kg ÷ ${additionalWeightKg}kg) = ${additionalUnits}个单位\n`;
                    formula += `4. 续重费用：${additionalUnits}个单位 × ¥${additionalWeightFee}/单位 = ¥${additionalFee}\n`;
                    formula += `5. 总运费：¥${firstWeightFee} + ¥${additionalFee} = ¥${result.freight}\n\n`;
                }
            }

            formula += '=== 计算完成 ===\n';
            formula += `最终运费：¥${result.freight}元`;

            return formula;
        };

        const resetFreightForm = () => {
            Object.assign(freightForm, {
                weight: null, length: null, width: null, height: null,
                fromAreaId: '', toAreaId: '',
                toProvinceName: '', // 重置地址层级字段
                toCityName: '',
                toDistrictName: '',
                strategyId: '', warehouseCode: '', logisticsCompanyCode: ''
            });
            freightResult.value = null;
            clearMessages();
            // 清空区域选择
            selectedProvince.value = null;
            selectedCity.value = null;
            selectedDistrict.value = null;
            showAreaSelector.value = false;
            // 重置策略搜索
            strategySearchKeyword.value = '';
            showStrategyDropdown.value = false;
            filteredStrategies.value = [];
        };

        // 数据加载方法

        // 区域管理页面专用的分页加载方法
        const loadAreasWithPage = async () => {
            try {
                console.log('🔄 加载区域数据（分页）...');

                // 构建查询参数，包含分页信息
                const queryParams = {
                    ...areaQuery,
                    currentPage: areaPagination.currentPage,
                    pageSize: areaPagination.pageSize
                };

                console.log('查询参数:', queryParams);
                const result = await api.getAreasWithPage(queryParams);

                if (result.code === 0) {
                    console.log('📊 API返回的原始数据:', result.data);

                    // 处理 PageUtils 格式的分页结果
                    if (result.data && typeof result.data === 'object') {
                        // PageUtils 数据结构
                        areas.value = result.data.list || [];
                        areaPagination.totalItems = result.data.totalSize || 0;
                        areaPagination.totalPages = result.data.totalPages || 0;
                        areaPagination.currentPage = result.data.currentPage || 1;
                        areaPagination.pageSize = result.data.pageSize || 10;

                        console.log('📊 分页信息更新后:', {
                            totalItems: areaPagination.totalItems,
                            totalPages: areaPagination.totalPages,
                            currentPage: areaPagination.currentPage,
                            pageSize: areaPagination.pageSize,
                            dataCount: areas.value.length
                        });
                    } else {
                        // 如果数据格式不正确，重置为空
                        areas.value = [];
                        areaPagination.totalItems = 0;
                        areaPagination.totalPages = 0;
                        areaPagination.currentPage = 1;
                        console.log('⚠️ 数据格式不正确，重置分页信息');
                    }

                    console.log('✅ 区域数据加载成功（分页）:', areas.value.length, '条，总数:', areaPagination.totalItems);
                    console.log('🔍 分页控件显示条件 totalPages > 1:', areaPagination.totalPages > 1);
                    buildAreaTree();
                } else {
                    areas.value = [];
                    areaPagination.totalItems = 0;
                    areaPagination.totalPages = 0;
                    showMessage('加载区域失败: ' + result.msg, true);
                }
            } catch (err) {
                console.error('❌ 加载区域失败:', err);
                areas.value = [];
                areaPagination.totalItems = 0;
                areaPagination.totalPages = 0;
                showMessage('加载区域失败', true);
            }
        };

        // 公共的区域数据加载方法（运费计算、策略映射等页面使用）
        const loadAreas = async () => {
            try {
                console.log('🔄 加载所有区域数据...');

                // 使用非分页接口获取所有区域数据
                const result = await api.getAreas();

                if (result.code === 0) {
                    areas.value = result.data || [];
                    console.log('✅ 所有区域数据加载成功:', areas.value.length, '条');
                    buildAreaTree();
                } else {
                    areas.value = [];
                    showMessage('加载区域失败: ' + result.msg, true);
                }
            } catch (err) {
                console.error('❌ 加载区域失败:', err);
                areas.value = [];
                showMessage('加载区域失败', true);
            }
        };

        const loadStrategies = async () => {
            try {
                console.log('🔄 加载策略数据...');
                const result = await api.getStrategies();
                if (result.code === 0) {
                    // 确保数据的安全性
                    strategies.value = (result.data || []).filter(strategy =>
                        strategy && typeof strategy === 'object' && strategy.name
                    );
                    console.log('✅ 策略数据加载成功:', strategies.value.length, '条');

                    // 初始化过滤结果
                    filteredStrategies.value = strategies.value;
                } else {
                    showMessage('加载策略失败: ' + result.msg, true);
                    // 在失败时确保数组为空
                    strategies.value = [];
                    filteredStrategies.value = [];
                }
            } catch (err) {
                console.error('❌ 加载策略失败:', err);
                showMessage('加载策略失败', true);
                // 在错误时确保数组为空
                strategies.value = [];
                filteredStrategies.value = [];
            }
        };

        const loadMappings = async () => {
            try {
                console.log('🔄 加载映射数据...');
                const result = await api.getMappings();
                if (result.code === 0) {
                    mappings.value = result.data || [];
                    console.log('✅ 映射数据加载成功:', mappings.value.length, '条');
                } else {
                    console.error('❌ 加载映射失败:', result.msg);
                }
            } catch (err) {
                console.error('❌ 加载映射失败:', err);
            }
        };

        const loadAssignments = async () => {
            try {
                console.log('🔄 加载分配数据...');

                // 同时加载分配和策略数据
                const [assignmentsResult, strategiesResult] = await Promise.all([
                    api.getAssignments(),
                    api.getStrategies()
                ]);

                if (assignmentsResult.code === 0) {
                    assignments.value = assignmentsResult.data || [];
                    console.log('✅ 分配数据加载成功:', assignments.value.length, '条');
                } else {
                    assignments.value = [];
                    console.error('❌ 加载分配失败:', assignmentsResult.msg);
                }

                if (strategiesResult.code === 0) {
                    const strategiesData = strategiesResult.data || [];
                    console.log('✅ 策略数据加载成功:', strategiesData.length, '条');

                    // 为分配中填充策略名称
                    (assignments.value || []).forEach(assignment => {
                        const strategy = strategiesData.find(s => s.id === assignment.strategyId);
                        assignment.strategyName = strategy ? strategy.name : '未知策略';
                    });

                    console.log('✅ 策略名称填充完成');
                } else {
                    console.error('❌ 加载策略失败:', strategiesResult.msg);
                    // 即使策略加载失败，也为分配设置默认策略名称
                    (assignments.value || []).forEach(assignment => {
                        assignment.strategyName = '未知策略';
                    });
                }
            } catch (err) {
                console.error('❌ 加载分配失败:', err);
                assignments.value = [];
            }
        };

        const loadWeightRules = async () => {
            if (!selectedStrategyId.value) {
                weightRules.value = [];
                return;
            }
            try {
                console.log('🔄 加载重量规则数据...', selectedStrategyId.value);
                const result = await api.getWeightRules(selectedStrategyId.value);
                if (result.code === 0) {
                    weightRules.value = result.data || [];
                    console.log('✅ 重量规则数据加载成功:', weightRules.value.length, '条');
                } else {
                    console.error('❌ 加载重量规则失败:', result.msg);
                }
            } catch (err) {
                console.error('❌ 加载重量规则失败:', err);
            }
        };

        // 重量规则页面专用的策略搜索功能
        const handleWeightRulesStrategySearch = (keyword) => {
            console.log('🔍 重量规则页面策略搜索:', keyword);

            if (!keyword || keyword.trim() === '') {
                // 空搜索时显示所有策略
                filteredWeightRulesStrategies.value = strategies.value || [];
            } else {
                // 有关键词时进行过滤
                const filtered = (strategies.value || []).filter(strategy =>
                    strategy && strategy.name && strategy.name.toLowerCase().includes(keyword.toLowerCase())
                );
                filteredWeightRulesStrategies.value = filtered;
            }

            showWeightRulesStrategyDropdown.value = true;
        };

        const showWeightRulesStrategyOptions = (keyword) => {
            console.log('🔍 显示策略选项:', keyword);
            // 聚焦时显示所有策略或按关键词过滤
            if (!keyword || keyword.trim() === '') {
                filteredWeightRulesStrategies.value = strategies.value || [];
            } else {
                handleWeightRulesStrategySearch(keyword);
            }
            showWeightRulesStrategyDropdown.value = true;
        };

        const hideWeightRulesStrategyDropdown = () => {
            setTimeout(() => {
                showWeightRulesStrategyDropdown.value = false;
            }, 200);
        };

        const clearWeightRulesSearch = () => {
            console.log('🧽 清空重量规则搜索');
            weightRulesSearchKeyword.value = '';
            filteredWeightRulesStrategies.value = [];
            showWeightRulesStrategyDropdown.value = false;
        };

        const handleWeightRulesStrategySelection = (strategy) => {
            console.log('🔧 重量规则页面选择策略:', strategy);
            if (!strategy || !strategy.name) {
                console.warn('无效的策略数据:', strategy);
                return;
            }

            // 仅仅更新搜索框的显示文本，不影响其他状态
            weightRulesSearchKeyword.value = strategy.name;
            showWeightRulesStrategyDropdown.value = false;
            filteredWeightRulesStrategies.value = [];
        };

        // 策略列表中的选择功能（不影响搜索框）
        const selectWeightRulesStrategy = (strategy) => {
            console.log('🔧 从策略列表选择策略:', strategy);
            if (!strategy || !strategy.id) {
                console.warn('无效的策略数据:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }

            // 仅更新选中的策略ID，不影响搜索框
            selectedStrategyId.value = strategy.id;

            // 加载对应的重量规则
            loadWeightRules();

            console.log('✅ 策略选择完成，已选中策略ID:', selectedStrategyId.value);
        };

        // 重量规则管理功能 - 核心修复
        const addWeightRuleForStrategy = (strategy) => {
            console.log('🔧 为策略新增重量规则:', strategy);
            if (!strategy || !strategy.id) {
                showMessage('无效的策略数据', true);
                return;
            }

            // 重置表单并设置策略信息
            Object.assign(weightRuleForm, {
                id: null,
                strategyId: strategy.id,
                strategyName: strategy.name || '未知策略',
                upperBound: null,
                freight: null
            });

            // 同时选中该策略
            selectedStrategyId.value = strategy.id;

            // 显示新增模态框
            showAddWeightRuleModal.value = true;

            console.log('✅ 重量规则表单已初始化:', weightRuleForm);
        };

        const deleteWeightRule = async (id) => {
            if (!confirm('确定要删除这个规则吗？')) return;

            try {
                console.log('🔧 删除重量规则:', id);
                const result = await api.deleteWeightRule({ id });
                if (result.code === 0) {
                    showMessage('删除成功');
                    loadWeightRules();
                } else {
                    showMessage(result.msg || '删除失败', true);
                }
            } catch (err) {
                console.error('❌ 删除重量规则失败:', err);
                showMessage(err.message, true);
            }
        };

        const editWeightRule = (rule) => {
            console.log('🔧 编辑重量规则:', rule);

            // 获取策略名称
            const strategy = strategies.value.find(s => s.id === rule.strategyId);
            const strategyName = strategy ? strategy.name : '未知策略';

            Object.assign(weightRuleForm, {
                id: rule.id,
                strategyId: rule.strategyId,
                strategyName: strategyName,
                upperBound: rule.upperBound,
                freight: rule.freight
            });
            showEditWeightRuleModal.value = true;

            console.log('✅ 编辑表单已初始化:', weightRuleForm);
        };

        const submitWeightRule = async () => {
            console.log('🔧 提交重量规则:', weightRuleForm);

            // 数据验证
            if (!weightRuleForm.upperBound || weightRuleForm.upperBound < 0) {
                showMessage('请输入有效的重量上限', true);
                return;
            }

            if (!weightRuleForm.freight || weightRuleForm.freight < 0) {
                showMessage('请输入有效的邮资', true);
                return;
            }

            submitting.value = true;
            try {
                // 确保策略ID
                if (!weightRuleForm.strategyId) {
                    weightRuleForm.strategyId = selectedStrategyId.value;
                }

                if (!weightRuleForm.strategyId) {
                    throw new Error('请先选择策略');
                }

                console.log('🚀 发送重量规则数据:', weightRuleForm);

                const apiMethod = weightRuleForm.id ? 'updateWeightRule' : 'addWeightRule';
                const result = await api[apiMethod](weightRuleForm);

                console.log('📥 重量规则提交响应:', result);

                if (result.code === 0) {
                    showMessage('操作成功');
                    closeWeightRuleModal();
                    loadWeightRules();
                } else {
                    showMessage(result.msg || '操作失败', true);
                }
            } catch (err) {
                console.error('❌ 重量规则提交失败:', err);
                showMessage(err.message || '提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        const closeWeightRuleModal = () => {
            showAddWeightRuleModal.value = false;
            showEditWeightRuleModal.value = false;
            Object.assign(weightRuleForm, {
                id: null, strategyId: '', strategyName: '', upperBound: null, freight: null
            });
        };

        // 区域树构建
        const buildAreaTree = () => {
            console.log('构建区域树...');

            if (areas.value.length === 0) {
                console.warn('区域数据为空，无法构建区域树');
                areaTree.value = [];
                return;
            }

            const tree = [];
            const provinces = (areas.value || []).filter(area => area.level === 1);

            provinces.forEach((province, index) => {
                const provinceId = province.areaId || province.id || province.code || `province_${index}`;
                const provinceName = province.provinceName || province.name || '未知省份';

                const provinceNode = {
                    id: provinceId,
                    name: provinceName,
                    children: []
                };

                // 查找城市
                const cities = (areas.value || []).filter(area =>
                    area.level === 2 && area.provinceCode === province.provinceCode
                );

                cities.forEach(city => {
                    const cityId = city.areaId || city.id || city.code;
                    const cityName = city.cityName || city.name || '未知城市';

                    const cityNode = {
                        id: cityId,
                        name: cityName,
                        children: []
                    };

                    // 查找区县
                    const districts = (areas.value || []).filter(area =>
                        area.level === 3 && area.cityCode === city.cityCode
                    );

                    districts.forEach(district => {
                        const districtId = district.areaId || district.id || district.code;
                        const districtName = district.districtName || district.name || '未知区县';

                        cityNode.children.push({
                            id: districtId,
                            name: districtName,
                            children: []
                        });
                    });

                    provinceNode.children.push(cityNode);
                });

                tree.push(provinceNode);
            });

            areaTree.value = tree;
            console.log('区域树构建完成:', tree.length, '个省份');
        };

        // 区域选择功能
        const toggleAreaSelector = () => {
            showAreaSelector.value = !showAreaSelector.value;
        };

        // 展开省份（不选择）
        const expandProvince = (province) => {
            if (!province || !province.name) {
                console.error('无效的省份数据:', province);
                return;
            }

            console.log('展开省份:', province.name);
            selectedProvince.value = province;
            selectedCity.value = null;
            selectedDistrict.value = null;
        };

        // 选择省份
        const selectProvince = (province) => {
            if (!province || !province.id) {
                console.error('无效的省份数据:', province);
                showMessage('无效的省份数据', true);
                return;
            }

            selectedProvince.value = province;
            selectedCity.value = null;
            selectedDistrict.value = null;
            freightForm.toAreaId = province.id;
            showAreaSelector.value = false;

            console.log('省份选择完成:', province.name);
        };

        // 展开城市（不选择）
        const expandCity = (city) => {
            if (!city || !city.name) {
                console.error('无效的城市数据:', city);
                return;
            }

            console.log('展开城市:', city.name);
            selectedCity.value = city;
            selectedDistrict.value = null;
        };

        // 选择城市
        const selectCity = (city) => {
            if (!city || !city.id || !city.name) {
                console.error('无效的城市数据:', city);
                showMessage('无效的城市数据', true);
                return;
            }

            console.log('选择城市:', city.name, '- 直接完成选择');
            selectedCity.value = city;
            selectedDistrict.value = null;
            // 直接设置目标区域并关闭选择器，允许只选择城市
            freightForm.toAreaId = city.id;
            showAreaSelector.value = false;
            console.log('城市选择完成，选择器已关闭:', {
                toAreaId: freightForm.toAreaId,
                cityName: city.name
            });
        };

        // 选择区县（保持原有逻辑）
        const selectDistrict = (district) => {
            console.log('选择区县:', district.name, '- 完成最细粒度选择');
            selectedDistrict.value = district;
            freightForm.toAreaId = district.id;
            showAreaSelector.value = false;
            console.log('区县选择完成，选择器已关闭:', {
                toAreaId: freightForm.toAreaId,
                districtName: district.name
            });
        };

        const clearAreaSelection = () => {
            selectedProvince.value = null;
            selectedCity.value = null;
            selectedDistrict.value = null;
            freightForm.toAreaId = '';
            showAreaSelector.value = false;
        };

        // 鼠标离开延迟定时器
        let mouseLeaveTimer = null;

        /**
         * 处理区域选择器鼠标离开事件
         */
        const handleAreaSelectorMouseLeave = () => {
            console.log('鼠标离开区域选择器');
            // 设置延迟关闭，给用户一个缓冲时间
            mouseLeaveTimer = setTimeout(() => {
                if (showAreaSelector.value) {
                    showAreaSelector.value = false;
                    console.log('鼠标离开后自动关闭选择器');
                }
            }, 300); // 300ms延迟，给用户缓冲时间
        };

        /**
         * 处理区域选择器鼠标进入事件
         */
        const handleAreaSelectorMouseEnter = () => {
            console.log('鼠标进入区域选择器');
            // 取消延迟关闭
            if (mouseLeaveTimer) {
                clearTimeout(mouseLeaveTimer);
                mouseLeaveTimer = null;
                console.log('取消延迟关闭');
            }
        };

        const getSelectedAreaText = () => {
            // 优先根据freightForm.toAreaId确定选中的区域
            if (freightForm.toAreaId) {
                // 尝试从区域数据中找到对应的区域
                const selectedArea = (areas.value || []).find(area => area.areaId === freightForm.toAreaId);
                if (selectedArea) {
                    return formatAreaName(selectedArea);
                }

                // 如果在areas中找不到，尝试从areaTree中查找
                if (selectedDistrict.value && selectedDistrict.value.id === freightForm.toAreaId) {
                    return `${selectedProvince.value.name}-${selectedCity.value.name}-${selectedDistrict.value.name}`;
                } else if (selectedCity.value && selectedCity.value.id === freightForm.toAreaId) {
                    return `${selectedProvince.value.name}-${selectedCity.value.name}`;
                } else if (selectedProvince.value && selectedProvince.value.id === freightForm.toAreaId) {
                    return selectedProvince.value.name;
                }

                // 如果找不到对应的区域信息，显示ID
                return `已选择区域 (ID: ${freightForm.toAreaId})`;
            }

            return '请选择区域';
        };

        // 策略搜索功能
        const handleStrategySearch = (keyword) => {
            strategySearchKeyword.value = keyword;
            if (!keyword.trim()) {
                // 确保过滤出有效的策略对象
                filteredStrategies.value = (strategies.value || []).filter(strategy =>
                    strategy && strategy.name
                );
            } else {
                // 过滤策略，添加安全检查
                filteredStrategies.value = (strategies.value || []).filter(strategy => {
                    if (!strategy || !strategy.name) {
                        return false;
                    }
                    return strategy.name.toLowerCase().includes(keyword.toLowerCase());
                });
            }
        };

        const showStrategyOptions = (keyword) => {
            handleStrategySearch(keyword);
            showStrategyDropdown.value = true;
        };

        const hideStrategyDropdown = () => {
            setTimeout(() => {
                showStrategyDropdown.value = false;
            }, 200);
        };

        const handleStrategySelection = (strategy, targetField) => {
            console.log('🎯 策略选择开始:', {
                strategy: strategy,
                targetField: targetField,
                currentSelectedId: selectedMappingStrategyId.value
            });

            // 添加策略对象的安全检查
            if (!strategy || !strategy.id || !strategy.name) {
                console.error('❌ 无效的策略对象:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }

            try {
                switch (targetField) {
                    case 'selectedStrategyId':
                        console.log('⚙️ 设置重量规则策略ID:', strategy.id);
                        selectedStrategyId.value = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 重量规则策略ID已设置:', selectedStrategyId.value);
                        loadWeightRules();
                        break;
                    case 'selectedMappingStrategyId':
                        console.log('🗺️ 开始设置映射策略ID:', strategy.id);
                        console.log('📊 设置前状态检查:', {
                            selectedMappingStrategyId_before: selectedMappingStrategyId.value,
                            strategySearchKeyword_before: strategySearchKeyword.value
                        });

                        selectedMappingStrategyId.value = strategy.id;
                        strategySearchKeyword.value = strategy.name;

                        console.log('📊 设置后状态检查:', {
                            selectedMappingStrategyId_after: selectedMappingStrategyId.value,
                            strategySearchKeyword_after: strategySearchKeyword.value
                        });

                        console.log('✅ 映射策略ID设置完成，开始加载映射详情...');

                        // 强制触发响应式更新
                        setTimeout(() => {
                            console.log('⏰ 延迟检查selectedMappingStrategyId:', selectedMappingStrategyId.value);
                            loadMappingDetails();
                        }, 100);
                        break;
                    case 'freightForm':
                        console.log('💼 设置运费表单策略ID:', strategy.id);
                        freightForm.strategyId = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 运费表单策略ID已设置:', freightForm.strategyId);
                        break;
                    case 'assignmentForm':
                        console.log('📋 设置分配表单策略ID:', strategy.id);
                        assignmentForm.strategyId = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 分配表单策略ID已设置:', assignmentForm.strategyId);
                        break;
                    case 'batchAssignmentForm':
                        console.log('📦 设置批量分配表单策略ID:', strategy.id);
                        batchAssignmentForm.strategyId = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 批量分配表单策略ID已设置:', batchAssignmentForm.strategyId);
                        break;
                    case 'mappingForm':
                        console.log('🗺️ 设置映射表单策略ID:', strategy.id);
                        mappingForm.strategyId = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 映射表单策略ID已设置:', mappingForm.strategyId);
                        loadWeightRulesForMapping();
                        break;
                    case 'batchMappingForm':
                        console.log('🗺️📦 设置批量映射表单策略ID:', strategy.id);
                        batchMappingForm.strategyId = strategy.id;
                        strategySearchKeyword.value = strategy.name;
                        console.log('✅ 批量映射表单策略ID已设置:', batchMappingForm.strategyId);
                        loadWeightRulesForBatch();
                        break;
                    default:
                        console.warn('⚠️ 未知的目标字段:', targetField);
                        break;
                }

                showStrategyDropdown.value = false;
                console.log('✅ 策略选择处理完成');

            } catch (error) {
                console.error('❌ 策略选择处理异常:', error);
                showMessage('策略选择失败: ' + error.message, true);
            }
        };

        // 标签切换
        const switchTab = (tabName) => {
            activeTab.value = tabName;

            // 当切换到映射管理页面时，自动选择第一个策略
            if (tabName === 'mapping') {
                // 延迟执行，确保DOM已更新
                nextTick(() => {
                    if (strategies.value && strategies.value.length > 0 && !selectedMappingStrategyId.value) {
                        const firstStrategy = strategies.value[0];
                        console.log('✅ 自动选择第一个策略:', firstStrategy);
                        selectStrategyFromList(firstStrategy);
                    }
                });
            }

            // 当切换到策略区域配置页面时，初始化数据
            if (tabName === 'area-config') {
                console.log('🔧 切换到策略区域配置页面，初始化数据');
                nextTick(() => {
                    // 重置选择状态
                    selectedAreaConfigStrategyId.value = '';
                    selectedAreaConfigAreaId.value = '';
                    selectedAreaDetail.value = null;
                    strategyAreaDetails.value = [];
                    isEditingAreaConfig.value = false;
                    strategySearchKeyword.value = '';
                });
            }

            // 当切换到V3策略配置页面时，初始化V3StrategyConfigManager（改为等待模块就绪事件）
            if (tabName === 'v3-strategy-config') {
                console.log('🔧 切换到V3策略配置页面，初始化V3StrategyConfigManager');

                // 添加详细的调试信息
                console.log('🔍 检查V3StrategyConfigManager模块状态:');
                console.log('  - window.V3StrategyConfigManager 存在:', !!window.V3StrategyConfigManager);
                console.log('  - init方法存在:', !!(window.V3StrategyConfigManager && window.V3StrategyConfigManager.init));
                console.log('  - 容器元素存在:', !!document.getElementById('v3-strategy-config-container'));

                nextTick(async () => {
                    try {
                        // 尝试立即初始化（快速路径）
                        const tryInit = async () => {
                            if (window.V3StrategyConfigManager && typeof window.V3StrategyConfigManager.init === 'function') {
                                console.log('✅ V3StrategyConfigManager模块检查通过，开始初始化...');
                                await window.V3StrategyConfigManager.init();
                                console.log('✅ V3StrategyConfigManager初始化成功');
                                return true;
                            }
                            return false;
                        };

                        if (await tryInit()) return;

                        // 监听模块就绪事件 (v3ModuleLoaded / v3FunctionsReady)，并同时轮询，带超时与回退
                        let completed = false;
                        const onReady = async () => {
                            if (completed) return;
                            if (await tryInit()) {
                                completed = true;
                                cleanup();
                            }
                        };

                        const cleanup = () => {
                            window.removeEventListener('v3ModuleLoaded', onReady);
                            window.removeEventListener('v3FunctionsReady', onReady);
                            clearInterval(pollTimer);
                            clearTimeout(timeoutTimer);
                        };

                        window.addEventListener('v3ModuleLoaded', onReady);
                        window.addEventListener('v3FunctionsReady', onReady);

                        // 轮询检查（每200ms）
                        const pollTimer = setInterval(async () => {
                            if (completed) return;
                            if (await tryInit()) {
                                completed = true;
                                cleanup();
                            }
                        }, 200);

                        // 超时后回退到原先的重试逻辑
                        const timeoutMs = 3000;
                        const timeoutTimer = setTimeout(async () => {
                            if (completed) return;
                            cleanup();

                            try {
                                let retryCount = 0;
                                const maxRetries = 3;
                                while (retryCount < maxRetries) {
                                    retryCount++;
                                    console.warn(`⚠️ V3StrategyConfigManager未准备就绪，第${retryCount}次重试...`);
                                    await new Promise(r => setTimeout(r, 100));
                                    if (await tryInit()) return;
                                }

                                console.error('❌ V3StrategyConfigManager加载检查失败，详细信息:');
                                console.error('  - window对象:', window);
                                console.error('  - V3StrategyConfigManager:', window.V3StrategyConfigManager);
                                console.error('  - 可用的全局对象:', Object.keys(window).filter(key => key.includes('V3')));
                                showMessage('V3策略配置模块未加载，请刷新页面重试', true);
                            } catch (err) {
                                console.error('❌ V3StrategyConfigManager初始化失败（回退重试阶段）:', err);
                                showMessage('V3策略配置初始化失败: ' + err.message, true);
                            }
                        }, timeoutMs);

                    } catch (error) {
                        console.error('❌ V3StrategyConfigManager初始化失败:', error);
                        console.error('错误详情:', error.stack);
                        showMessage('V3策略配置初始化失败: ' + error.message, true);
                    }
                });
            }

            // 当切换到区域管理页面时，加载分页数据
            if (tabName === 'area') {
                console.log('🏢 切换到区域管理页面，加载分页数据');
                // 延迟执行，确保DOM已更新
                nextTick(() => {
                    loadAreasWithPage();
                });
            }

            // 当切换到操作日志页面时，跳转到单独的操作日志页面
            if (tabName === 'operation-log') {
                console.log('📈 切换到操作日志页面，跳转到operation-log.html');
                window.location.href = 'operation-log.html';
                return;
            }
        };

        // 策略管理功能
        const addStrategy = () => {
            showAddStrategyModal.value = true;
        };

        // 复制并新建策略
        const copyAndCreateStrategy = (strategy) => {
            if (!strategy || !strategy.id) {
                console.error('无效的策略数据:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }

            // 设置当前复制的策略
            currentStrategyForCopy.value = strategy;

            // 填充复制策略表单数据
            Object.assign(copyStrategyForm, {
                id: strategy.id,
                newName: strategy.name + '_副本',
                description: strategy.description || '',
                operator: 'system'
            });
            copyStrategyForm.newName = strategy.name + '_副本';
            copyStrategyForm.description = strategy.description || '';

            showCopyStrategyModal.value = true;
            console.log('📋 复制策略:', strategy.name);
            console.log('📋 复制策略:',copyStrategyForm);
        };

        // 关闭复制策略弹框
        const closeCopyStrategyModal = () => {
            console.log('DEBUG: closeCopyStrategyModal 方法被调用');
            showCopyStrategyModal.value = false;
            console.log('DEBUG: showCopyStrategyModal.value 设置为', showCopyStrategyModal.value);
            copyStrategyForm.id = null;
            copyStrategyForm.newName = '';
            copyStrategyForm.description = '';
            copyStrategyForm.newName = '';
            copyStrategyForm.description = '';
            currentStrategyForCopy.value = null;
            console.log('DEBUG: 复制策略弹框状态已重置');
        };

        // 提交复制策略
        const submitCopyStrategy = async () => {
            if (!copyStrategyForm.newName || !copyStrategyForm.newName.trim()) {
                showMessage('请输入新策略名称', true);
                return;
            }

            if (!copyStrategyForm.id) {
                showMessage('无效的策略ID', true);
                return;
            }

            submitting.value = true;
            try {
                const result = await api.copyStrategyData({
                    id: copyStrategyForm.id,
                    newName: copyStrategyForm.newName.trim(),
                    description: copyStrategyForm.description.trim()
                });

                if (result.code === 0) {
                    showMessage('复制策略成功');
                    closeCopyStrategyModal();
                    loadStrategies(); // 重新加载策略列表
                } else {
                    showMessage(result.msg || '复制策略失败', true);
                }
            } catch (err) {
                console.error('复制策略失败:', err);
                showMessage('复制策略失败: ' + (err.message || '网络错误'), true);
            } finally {
                submitting.value = false;
            }
        };

        // 在映射页面中编辑策略
        const editStrategyInMapping = (strategy) => {
            if (!strategy || !strategy.id) {
                console.error('无效的策略数据:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }

            // 填充策略表单数据
            Object.assign(strategyForm, {
                id: strategy.id,
                name: strategy.name,
                description: strategy.description,
                pricingModel: strategy.pricingModel,
                status: strategy.status
            });

            showEditStrategyModal.value = true;
            console.log('✏️ 在映射页面中编辑策略:', strategy.name);
        };

        const addWeightRule = () => {
            if (!selectedStrategyId.value) {
                showMessage('请先在左侧策略列表中选择一个策略，然后再新增规则', true);
                return;
            }
            showAddWeightRuleModal.value = true;
        };

        const addMapping = () => {
            // 重置映射表单
            Object.assign(mappingForm, {
                strategyId: '',
                areaId: '',
                segmentRuleIds: []
            });

            // 清空级联选择器状态
            cascaderState.selectedProvinces.clear();
            cascaderState.selectedCities.clear();
            cascaderState.selectedDistricts.clear();
            cascaderState.expandedProvinces.clear();
            cascaderState.expandedCities.clear();

            // 确保区域树已构建
            buildAreaTree();

            // 如果已选择策略，自动设置到表单中
            if (selectedMappingStrategyId.value) {
                mappingForm.strategyId = selectedMappingStrategyId.value;
                loadWeightRulesForMapping();
            }

            showAddMappingModal.value = true;
            console.log('✅ 新增映射模态框已打开，区域树已初始化');
        };

        const addBatchMappings = () => {
            // 重置批量映射表单
            Object.assign(batchMappingForm, {
                strategyId: '',
                areaIds: [],
                segmentRuleIds: []
            });

            // 清空级联选择器状态
            cascaderState.selectedProvinces.clear();
            cascaderState.selectedCities.clear();
            cascaderState.selectedDistricts.clear();
            cascaderState.expandedProvinces.clear();
            cascaderState.expandedCities.clear();

            // 确保区域树已构建
            buildAreaTree();

            // 如果已选择策略，自动设置到表单中
            if (selectedMappingStrategyId.value) {
                batchMappingForm.strategyId = selectedMappingStrategyId.value;
                loadWeightRulesForBatch();
            }

            showBatchMappingModal.value = true;
            console.log('✅ 批量映射模态框已打开，区域树已初始化');
        };

        const addAssignment = () => {
            // 清空策略搜索关键词，避免默认回显
            strategySearchKeyword.value = '';
            showAddAssignmentModal.value = true;
        };

        const addBatchAssignments = () => {
            // 清空策略搜索关键词，避免默认回显
            strategySearchKeyword.value = '';
            showBatchAssignmentModal.value = true;
        };

        // ===================================
        // 策略区域配置页面方法
        // ===================================

        // 策略选择处理
        const handleAreaConfigStrategySelection = async (strategy) => {
            try {
                console.log('🔧 选择策略用于区域配置:', strategy);
                selectedAreaConfigStrategyId.value = strategy.id;
                strategySearchKeyword.value = strategy.name;
                showStrategyDropdown.value = false;

                // 加载策略的区域详情
                await loadStrategyAreaDetails();
            } catch (error) {
                console.error('❗ 策略选择失败:', error);
                showMessage('策略选择失败: ' + error.message, true);
            }
        };

        // 加载策略的区域详情列表
        const loadStrategyAreaDetails = async () => {
            if (!selectedAreaConfigStrategyId.value) return;

            try {
                console.log('📄 加载策略区域详情:', selectedAreaConfigStrategyId.value);
                const result = await api.get(`/strategy-area-pricing/strategy/${selectedAreaConfigStrategyId.value}/area-details`);

                if (result.code === 0) {
                    strategyAreaDetails.value = result.data || [];
                    console.log('✅ 加载区域详情成功:', strategyAreaDetails.value.length, '个区域');
                } else {
                    strategyAreaDetails.value = [];
                    showMessage('加载区域详情失败: ' + result.msg, true);
                }
            } catch (error) {
                console.error('❗ 加载区域详情失败:', error);
                strategyAreaDetails.value = [];
                showMessage('加载区域详情失败', true);
            }
        };

        // 选择区域进行配置
        const selectAreaForConfig = (areaDetail) => {
            console.log('🏢 选择区域进行配置:', areaDetail);
            selectedAreaConfigAreaId.value = areaDetail.areaId;
            selectedAreaDetail.value = areaDetail;

            // 填充表单数据
            Object.assign(areaConfigForm, {
                strategyId: selectedAreaConfigStrategyId.value,
                areaId: areaDetail.areaId,
                areaName: areaDetail.areaName,
                firstWeightKg: areaDetail.firstWeightKg || '',
                firstWeightFee: areaDetail.firstWeightFee || '',
                additionalWeightKg: areaDetail.additionalWeightKg || '',
                additionalWeightFee: areaDetail.additionalWeightFee || '',
                volumetricWeightRatio: areaDetail.volumetricWeightRatio || '',
                status: areaDetail.status || 1,
                weightSegmentRules: [...(areaDetail.weightSegmentRules || [])]
            });

            // 更新当前重量区间规则
            currentWeightSegmentRules.value = [...(areaDetail.weightSegmentRules || [])];

            // 退出编辑模式
            isEditingAreaConfig.value = false;
        };

        // 开始编辑区域配置
        const startEditingAreaConfig = () => {
            if (!selectedAreaDetail.value) {
                showMessage('请先选择一个区域', true);
                return;
            }
            isEditingAreaConfig.value = true;
            console.log('✏️ 开始编辑区域配置:', selectedAreaDetail.value.areaName);
        };

        // 取消编辑区域配置
        const cancelEditingAreaConfig = () => {
            isEditingAreaConfig.value = false;
            // 重新填充表单数据
            if (selectedAreaDetail.value) {
                selectAreaForConfig(selectedAreaDetail.value);
            }
            console.log('❌ 取消编辑区域配置');
        };

        // 保存区域配置
        const saveAreaConfig = async () => {
            try {
                // 验证表单数据
                if (!areaConfigForm.firstWeightKg || parseFloat(areaConfigForm.firstWeightKg) < 0) {
                    showMessage('请输入有效的首重重量', true);
                    return;
                }

                if (!areaConfigForm.firstWeightFee || parseFloat(areaConfigForm.firstWeightFee) < 0) {
                    showMessage('请输入有效的首重费用', true);
                    return;
                }

                if (!areaConfigForm.additionalWeightKg || parseFloat(areaConfigForm.additionalWeightKg) < 0) {
                    showMessage('请输入有效的续重重量', true);
                    return;
                }

                if (!areaConfigForm.additionalWeightFee || parseFloat(areaConfigForm.additionalWeightFee) < 0) {
                    showMessage('请输入有效的续重费用', true);
                    return;
                }

                if (!areaConfigForm.volumetricWeightRatio || parseFloat(areaConfigForm.volumetricWeightRatio) < 0) {
                    showMessage('请输入有效的抛重比', true);
                    return;
                }

                savingAreaConfig.value = true;

                // 构造保存数据
                const configData = {
                    strategyId: selectedAreaConfigStrategyId.value,
                    areaId: selectedAreaConfigAreaId.value,
                    firstWeightKg: parseFloat(areaConfigForm.firstWeightKg),
                    firstWeightFee: parseFloat(areaConfigForm.firstWeightFee),
                    additionalWeightKg: parseFloat(areaConfigForm.additionalWeightKg),
                    additionalWeightFee: parseFloat(areaConfigForm.additionalWeightFee),
                    volumetricWeightRatio: parseFloat(areaConfigForm.volumetricWeightRatio),
                    status: areaConfigForm.status,
                    weightSegmentRules: currentWeightSegmentRules.value.map(rule => ({
                        id: rule.id || null,
                        upperBound: parseFloat(rule.upperBound),
                        freight: parseFloat(rule.freight),
                        operation: rule.id ? 'UPDATE' : 'ADD'
                    })),
                    operator: 'admin'
                };

                console.log('💾 保存区域配置数据:', configData);
                const result = await api.post('/strategy-area-pricing/complete-config/save', configData);

                if (result.code === 0) {
                    showMessage('保存成功');
                    isEditingAreaConfig.value = false;
                    // 重新加载数据
                    await loadStrategyAreaDetails();
                } else {
                    showMessage('保存失败: ' + result.msg, true);
                }
            } catch (error) {
                console.error('❗ 保存区域配置失败:', error);
                showMessage('保存失败: ' + error.message, true);
            } finally {
                savingAreaConfig.value = false;
            }
        };

        // 显示新增重量区间规则模态框
        const showAddWeightSegmentRule = () => {
            Object.assign(weightSegmentForm, {
                id: null,
                upperBound: '',
                freight: ''
            });
            showAddWeightSegmentModal.value = true;
        };

        // 编辑重量区间规则
        const editWeightSegmentRule = (rule, index) => {
            Object.assign(weightSegmentForm, {
                id: rule.id,
                upperBound: rule.upperBound,
                freight: rule.freight,
                index: index
            });
            showEditWeightSegmentModal.value = true;
        };

        // 删除重量区间规则
        const removeWeightSegmentRule = (index) => {
            if (confirm('确定要删除这个重量区间规则吗？')) {
                currentWeightSegmentRules.value.splice(index, 1);
                areaConfigForm.weightSegmentRules.splice(index, 1);
                console.log('✅ 已删除重量区间规则');
            }
        };

        // 关闭重量区间规则模态框
        const closeWeightSegmentModal = () => {
            showAddWeightSegmentModal.value = false;
            showEditWeightSegmentModal.value = false;
            Object.assign(weightSegmentForm, {
                id: null,
                upperBound: '',
                freight: ''
            });
        };

        // 提交重量区间规则
        const submitWeightSegmentRule = async () => {
            try {
                // 验证表单数据
                if (!weightSegmentForm.upperBound || parseFloat(weightSegmentForm.upperBound) < 0) {
                    showMessage('请输入有效的重量上限', true);
                    return;
                }

                if (!weightSegmentForm.freight || parseFloat(weightSegmentForm.freight) < 0) {
                    showMessage('请输入有效的区间资费', true);
                    return;
                }

                const newRule = {
                    id: weightSegmentForm.id || null,
                    upperBound: weightSegmentForm.upperBound,
                    freight: weightSegmentForm.freight,
                    weightRangeDisplay: `≤${weightSegmentForm.upperBound} kg`
                };

                if (showEditWeightSegmentModal.value && weightSegmentForm.index !== undefined) {
                    // 编辑模式
                    currentWeightSegmentRules.value[weightSegmentForm.index] = newRule;
                    areaConfigForm.weightSegmentRules[weightSegmentForm.index] = newRule;
                } else {
                    // 新增模式
                    currentWeightSegmentRules.value.push(newRule);
                    areaConfigForm.weightSegmentRules.push(newRule);

                    // 按重量上限排序
                    currentWeightSegmentRules.value.sort((a, b) => parseFloat(a.upperBound) - parseFloat(b.upperBound));
                    areaConfigForm.weightSegmentRules.sort((a, b) => parseFloat(a.upperBound) - parseFloat(b.upperBound));
                }

                closeWeightSegmentModal();
                console.log('✅ 重量区间规则已更新');
            } catch (error) {
                console.error('❗ 提交重量区间规则失败:', error);
                showMessage('提交失败: ' + error.message, true);
            }
        };

        // 批量映射功能补充
        const submitBatchMapping = async () => {
            try {
                console.log('提交批量映射数据:', batchMappingForm);

                // 数据验证
                if (!batchMappingForm.strategyId) {
                    showMessage('请选择策略', true);
                    return;
                }

                if (!batchMappingForm.areaIds || batchMappingForm.areaIds.length === 0) {
                    showMessage('请至少选择一个区域', true);
                    return;
                }

                if (!batchMappingForm.segmentRuleIds || batchMappingForm.segmentRuleIds.length === 0) {
                    showMessage('请至少选择一个重量区间规则', true);
                    return;
                }

                submitting.value = true;

                // 检查是否为编辑模式
                if (batchMappingForm.editMode && batchMappingForm.originalAreaIds) {
                    // 编辑模式：差异化更新
                    console.log('编辑模式：进行差异化更新');

                    const currentAreaIds = batchMappingForm.areaIds;
                    const originalAreaIds = batchMappingForm.originalAreaIds;
                    const ruleId = batchMappingForm.segmentRuleIds[0];

                    // 计算需要删除和新增的区域
                    const toDelete = originalAreaIds.filter(id => !currentAreaIds.includes(id));
                    const toAdd = currentAreaIds.filter(id => !originalAreaIds.includes(id));

                    console.log('需要删除的区域:', toDelete);
                    console.log('需要新增的区域:', toAdd);

                    // 1. 删除不再选择的映射
                    if (toDelete.length > 0) {
                        const mappingData = await api.getMappings({ strategyId: batchMappingForm.strategyId });
                        const allMappings = mappingData.code === 0 ? mappingData.data : [];

                        const mappingIdsToDelete = [];
                        for (const areaId of toDelete) {
                            const mapping = allMappings.find(m =>
                                m.areaId === areaId &&
                                m.segmentRuleId === ruleId &&
                                m.strategyId === batchMappingForm.strategyId
                            );

                            if (mapping) {
                                mappingIdsToDelete.push(mapping.id);
                            }
                        }

                        // 使用批量删除接口
                        if (mappingIdsToDelete.length > 0) {
                            console.log('🗑️ 批量映射批量删除，ID列表:', mappingIdsToDelete);
                            const deleteResult = await api.batchDeleteMappings(mappingIdsToDelete);
                            if (deleteResult.code !== 0) {
                                console.error('批量删除映射失败:', deleteResult.msg);
                                showMessage('删除原有映射失败: ' + deleteResult.msg, true);
                                return;
                            }
                            console.log('✅ 批量映射成功删除', deleteResult.data, '个映射');
                        }
                    }

                    // 2. 添加新选择的映射
                    if (toAdd.length > 0) {
                        const addMappingData = {
                            strategyId: batchMappingForm.strategyId,
                            areaIds: toAdd,
                            segmentRuleIds: [ruleId]
                        };

                        console.log('批量添加映射:', addMappingData);
                        const addResult = await api.addBatchMappings(addMappingData);

                        if (addResult.code !== 0) {
                            showMessage('添加新映射失败: ' + addResult.msg, true);
                            return;
                        }
                    }

                    showMessage('映射编辑成功');
                } else {
                    // 新增模式：直接批量创建
                    const result = await api.addBatchMappings(batchMappingForm);

                    if (result.code === 0) {
                        showMessage('批量映射创建成功');
                    } else {
                        showMessage(result.msg || '批量映射创建失败', true);
                        return;
                    }
                }

                closeBatchMappingModal();
                await loadMappingDetails();

            } catch (err) {
                console.error('批量映射提交失败:', err);
                showMessage(err.message || '批量映射提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        const submitBatchAssignment = async () => {
            try {
                console.log('提交批量分配数据:', batchAssignmentForm);

                // 数据验证
                if (!batchAssignmentForm.strategyId) {
                    showMessage('请选择策略', true);
                    return;
                }

                if (!batchAssignmentForm.warehouseCodesText || !batchAssignmentForm.warehouseCodesText.trim()) {
                    showMessage('请输入仓库编码（多个用逗号分隔）', true);
                    return;
                }

                if (!batchAssignmentForm.logisticsCompanyCodesText || !batchAssignmentForm.logisticsCompanyCodesText.trim()) {
                    showMessage('请输入物流公司编码（多个用逗号分隔）', true);
                    return;
                }

                submitting.value = true;

                // 解析编码列表
                const warehouseCodes = batchAssignmentForm.warehouseCodesText
                    .split(',')
                    .map(code => code.trim())
                    .filter(code => code.length > 0);

                const logisticsCompanyCodes = batchAssignmentForm.logisticsCompanyCodesText
                    .split(',')
                    .map(code => code.trim())
                    .filter(code => code.length > 0);

                const data = {
                    strategyId: batchAssignmentForm.strategyId,
                    warehouseCodes: warehouseCodes,
                    logisticsCompanyCodes: logisticsCompanyCodes,
                    status: batchAssignmentForm.status || 1
                };

                const result = await api.batchAssign(data);

                if (result.code === 0) {
                    showMessage('批量分配创建成功');
                    closeBatchAssignmentModal();
                    await loadAssignments();
                } else {
                    showMessage(result.msg || '批量分配创建失败', true);
                }
            } catch (err) {
                console.error('批量分配提交失败:', err);
                showMessage(err.message || '批量分配提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        // 其他缺失的方法存根
        const loadWeightRulesForMapping = async () => {
            if (!selectedMappingStrategyId.value) {
                console.log('未选择策略，无法加载重量规则');
                return;
            }

            try {
                console.log('加载映射重量规则，策略ID:', selectedMappingStrategyId.value);
                const result = await api.getWeightRules(selectedMappingStrategyId.value);

                if (result.code === 0) {
                    // 将重量规则数据存储到mappingMergedData中
                    const rules = result.data || [];
                    mappingMergedData.value = rules.map(rule => ({
                        ruleId: rule.id,
                        upperBound: rule.upperBound,
                        freight: rule.freight,
                        strategyId: rule.strategyId,
                        areasDisplay: '所有区域', // 默认显示，可根据实际需要调整
                        areas: [] // 空数组，表示应用于所有区域
                    }));
                    console.log('映射重量规则加载成功:', rules.length, '条');
                } else {
                    console.error('加载映射重量规则失败:', result.msg);
                    mappingMergedData.value = [];
                }
            } catch (err) {
                console.error('加载映射重量规则失败:', err);
                mappingMergedData.value = [];
            }
        };

        const loadWeightRulesForBatch = async () => {
            if (!batchMappingForm.strategyId) {
                console.log('未选择策略，无法加载重量规则');
                batchWeightRules.value = [];
                return;
            }

            try {
                console.log('加载批量重量规则，策略ID:', batchMappingForm.strategyId);
                const result = await api.getWeightRules(batchMappingForm.strategyId);

                if (result.code === 0) {
                    batchWeightRules.value = result.data || [];
                    console.log('批量重量规则加载成功:', batchWeightRules.value.length, '条');
                } else {
                    console.error('加载批量重量规则失败:', result.msg);
                    batchWeightRules.value = [];
                }
            } catch (err) {
                console.error('加载批量重量规则失败:', err);
                batchWeightRules.value = [];
            }
        };

        const closeMappingModal = () => {
            showAddMappingModal.value = false;
        };

        const closeBatchMappingModal = () => {
            showBatchMappingModal.value = false;

            // 清空编辑模式相关状态
            batchMappingForm.editMode = false;
            batchMappingForm.originalAreaIds = [];

            // 清空区域选择状态
            cascaderState.selectedProvinces.clear();
            cascaderState.selectedCities.clear();
            cascaderState.selectedDistricts.clear();
        };

        const closeEditMappingModal = () => {
            showEditMappingModal.value = false;

            // 清空编辑模式相关状态
            batchMappingForm.editMode = false;
            batchMappingForm.originalAreaIds = [];

            // 清空区域选择状态
            cascaderState.selectedProvinces.clear();
            cascaderState.selectedCities.clear();
            cascaderState.selectedDistricts.clear();
        };

        const closeAssignmentModal = () => {
            showAddAssignmentModal.value = false;
        };

        const closeBatchAssignmentModal = () => {
            showBatchAssignmentModal.value = false;
        };

        // 批量分配预览计算
        const getBatchAssignmentPreviewCount = () => {
            if (!batchAssignmentForm.warehouseCodesText || !batchAssignmentForm.logisticsCompanyCodesText) {
                return 0;
            }

            const warehouseCodes = batchAssignmentForm.warehouseCodesText
                .split(',')
                .map(code => code.trim())
                .filter(code => code.length > 0);

            const logisticsCompanyCodes = batchAssignmentForm.logisticsCompanyCodesText
                .split(',')
                .map(code => code.trim())
                .filter(code => code.length > 0);

            return warehouseCodes.length * logisticsCompanyCodes.length;
        };

        // 提交单个映射
        const submitMapping = async () => {
            try {
                console.log('提交映射数据:', mappingForm);

                // 基本字段验证
                if (!mappingForm.strategyId) {
                    showMessage('请选择策略', true);
                    return;
                }

                if (!mappingForm.areaId) {
                    showMessage('请选择区域', true);
                    return;
                }

                // 重量规则验证
                if (!mappingForm.segmentRuleIds || mappingForm.segmentRuleIds.length === 0) {
                    console.error('重量规则ID为空或未选择:', mappingForm.segmentRuleIds);
                    showMessage('请至少选择一个重量规则', true);
                    return;
                }

                submitting.value = true;

                // 使用批量映射API，支持单区域多重量规则
                const batchData = {
                    strategyId: Number(mappingForm.strategyId),
                    areaIds: [Number(mappingForm.areaId)],
                    segmentRuleIds: mappingForm.segmentRuleIds.map(id => Number(id))
                };

                console.log('最终提交数据:', batchData);

                const result = await api.addBatchMappings(batchData);

                if (result.code === 0 || result.code === '0') {
                    showMessage('映射创建成功');
                    closeMappingModal();
                    await loadMappings();
                } else {
                    const errorMsg = result.msg || result.message || '映射创建失败';
                    console.error('映射创建失败:', errorMsg);
                    showMessage(errorMsg, true);
                }
            } catch (err) {
                console.error('映射提交失败:', err);

                let errorMessage = '映射提交失败';
                if (err.message.includes('重量区间规则ID不能为空')) {
                    errorMessage = '请选择至少一个重量区间规则';
                } else {
                    errorMessage = err.message || '未知错误';
                }

                showMessage(errorMessage, true);
            } finally {
                submitting.value = false;
            }
        };

        // 提交编辑映射
        const submitEditMapping = async () => {
            try {
                console.log('提交编辑映射数据:', editMappingForm);

                // 验证必要字段
                if (!editMappingForm.strategyId) {
                    showMessage('请选择策略', true);
                    return;
                }

                // 从当前区域选择状态获取选中的区域ID列表
                const currentAreaIds = [];

                // 添加选中的省份
                cascaderState.selectedProvinces.forEach(id => {
                    if (!currentAreaIds.includes(id)) {
                        currentAreaIds.push(id);
                    }
                });

                // 添加选中的城市
                cascaderState.selectedCities.forEach(id => {
                    if (!currentAreaIds.includes(id)) {
                        currentAreaIds.push(id);
                    }
                });

                // 添加选中的区县
                cascaderState.selectedDistricts.forEach(id => {
                    if (!currentAreaIds.includes(id)) {
                        currentAreaIds.push(id);
                    }
                });

                console.log('当前选中的区域ID列表:', currentAreaIds);

                if (currentAreaIds.length === 0) {
                    showMessage('请至少选择一个区域', true);
                    return;
                }

                submitting.value = true;

                // 使用编辑模式的批量映射提交逻辑（差异化更新）
                const originalAreaIds = editMappingForm.originalAreas || [];
                const ruleId = editMappingForm.ruleId;

                // 计算需要删除和新增的区域（差异化更新策略）
                const toDelete = originalAreaIds.filter(id => !currentAreaIds.includes(id));
                const toAdd = currentAreaIds.filter(id => !originalAreaIds.includes(id));

                console.log('差异化更新统计:', {
                    原始区域数量: originalAreaIds.length,
                    当前区域数量: currentAreaIds.length,
                    需要删除: toDelete.length,
                    需要新增: toAdd.length
                });
                console.log('需要删除的区域:', toDelete);
                console.log('需要新增的区域:', toAdd);

                // 1. 删除不再选择的映射（差异化更新：未选择的区域会被自动删除）
                if (toDelete.length > 0) {
                    const mappingData = await api.getMappings({ strategyId: editMappingForm.strategyId });
                    const allMappings = mappingData.code === 0 ? mappingData.data : [];

                    const mappingIdsToDelete = [];
                    for (const areaId of toDelete) {
                        const mapping = allMappings.find(m =>
                            m.areaId === areaId &&
                            m.segmentRuleId === ruleId &&
                            m.strategyId === editMappingForm.strategyId
                        );

                        if (mapping) {
                            mappingIdsToDelete.push(mapping.id);
                        }
                    }

                    // 使用批量删除接口
                    if (mappingIdsToDelete.length > 0) {
                        console.log('🗑️ 编辑模式批量删除映射，ID列表:', mappingIdsToDelete);
                        const deleteResult = await api.batchDeleteMappings(mappingIdsToDelete);
                        if (deleteResult.code !== 0) {
                            console.error('批量删除映射失败:', deleteResult.msg);
                            showMessage('删除原有映射失败: ' + deleteResult.msg, true);
                            return;
                        }
                        console.log('✅ 成功删除', deleteResult.data, '个映射');
                    }
                }

                // 2. 添加新选择的映射（差异化更新：新增的区域会被添加）
                if (toAdd.length > 0) {
                    const addMappingData = {
                        strategyId: editMappingForm.strategyId,
                        areaIds: toAdd,
                        segmentRuleIds: [ruleId]
                    };

                    console.log('批量添加映射:', addMappingData);
                    const addResult = await api.addBatchMappings(addMappingData);

                    if (addResult.code !== 0) {
                        showMessage('添加新映射失败: ' + addResult.msg, true);
                        return;
                    }
                }

                const deletedCount = toDelete.length;
                const addedCount = toAdd.length;
                let successMessage = '映射编辑成功';

                if (deletedCount > 0 || addedCount > 0) {
                    const operations = [];
                    if (deletedCount > 0) operations.push(`删除${deletedCount}个区域`);
                    if (addedCount > 0) operations.push(`添加${addedCount}个区域`);
                    successMessage = `映射编辑成功（${operations.join('、')}）`;
                } else {
                    successMessage = '映射无变化';
                }

                showMessage(successMessage);
                closeEditMappingModal();
                await loadMappingDetails();

            } catch (err) {
                console.error('编辑映射提交失败:', err);
                showMessage(err.message || '编辑映射失败', true);
            } finally {
                submitting.value = false;
            }
        };

        // 提交单个分配
        const submitAssignment = async () => {
            try {
                console.log('提交分配数据:', assignmentForm);

                if (!assignmentForm.strategyId) {
                    showMessage('请选择策略', true);
                    return;
                }

                if (!assignmentForm.warehouseCode) {
                    showMessage('请输入仓库编码', true);
                    return;
                }

                if (!assignmentForm.logisticsCompanyCode) {
                    showMessage('请输入物流公司编码', true);
                    return;
                }

                submitting.value = true;

                const result = await api.addAssignment(assignmentForm);

                if (result.code === 0) {
                    showMessage('分配创建成功');
                    closeAssignmentModal();
                    await loadAssignments();
                } else {
                    showMessage(result.msg || '分配创建失败', true);
                }
            } catch (err) {
                console.error('分配提交失败:', err);
                showMessage(err.message || '分配提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        // 策略管理相关方法
        const searchStrategies = async () => {
            try {
                console.log('执行策略查询，查询条件:', strategyQuery);

                // 调用API进行查询
                const result = await api.getStrategies(strategyQuery);

                if (result.code === 0) {
                    // 确保数据的安全性
                    strategies.value = (result.data || []).filter(strategy =>
                        strategy && typeof strategy === 'object' && strategy.name
                    );

                    const resultCount = strategies.value.length;
                    console.log('策略查询完成，结果数量:', resultCount);

                    if (resultCount === 0) {
                        showMessage('查询成功，找到 0 条记录');
                    } else {
                        showMessage(`查询成功，找到 ${resultCount} 条记录`);
                    }
                } else {
                    // API失败时也要清空数据
                    strategies.value = [];
                    showMessage('查询失败: ' + result.msg, true);
                }
            } catch (err) {
                console.error('策略查询失败:', err);
                // 请求异常时也要清空数据
                strategies.value = [];
                showMessage('查询失败', true);
            }
        };

        const resetStrategyQuery = async () => {
            Object.assign(strategyQuery, {
                name: '',
                pricingModel: '',
                status: ''
            });
            console.log('重置策略查询条件，重新加载所有数据');
            await loadStrategies();
            showMessage('已重置查询条件');
        };

        const editStrategy = (strategy) => {
            if (!strategy || !strategy.id) {
                console.error('无效的策略数据:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }
            console.log('编辑策略:', strategy.name);
            Object.assign(strategyForm, strategy);
            showEditStrategyModal.value = true;
        };

        const deleteStrategy = async (id) => {
            if (!id) {
                showMessage('无效的策略ID', true);
                return;
            }
            if (!confirm('确定要删除这个策略吗？')) return;

            try {
                const result = await api.deleteStrategy(id);
                if (result.code === 0) {
                    showMessage('删除成功');
                    await loadStrategies();
                    
                    // 刷新V3策略配置页面的策略列表
                    if (window.V3StrategyConfigManager && window.V3StrategyConfigManager.init) {
                        console.log('🔄 刷新V3策略配置页面数据...');
                        await window.V3StrategyConfigManager.init();
                    }
                    
                    // 清空当前选中的策略
                    if (this.v3CurrentStrategy) {
                        this.v3CurrentStrategy = null;
                    }
                } else {
                    showMessage(result.msg || '删除失败', true);
                }
            } catch (err) {
                console.error('删除策略失败:', err);
                showMessage(err.message, true);
            }
        };

        const toggleStrategyStatus = async (strategy) => {
            if (!strategy || !strategy.id || strategy.status === undefined) {
                console.error('无效的策略数据:', strategy);
                showMessage('无效的策略数据', true);
                return;
            }

            const newStatus = strategy.status === 1 ? 2 : 1;
            const statusText = newStatus === 1 ? '启用' : '禁用';

            if (!confirm(`确定要${statusText}这个策略吗？`)) return;

            try {
                const updateData = { ...strategy, status: newStatus };
                const result = await api.updateStrategy(updateData);
                if (result.code === 0) {
                    showMessage(`${statusText}成功`);
                    await loadStrategies();
                } else {
                    showMessage(result.msg || `${statusText}失败`, true);
                }
            } catch (err) {
                showMessage(err.message, true);
            }
        };

        const getStrategyStatusText = (status) => {
            if (status === undefined || status === null) return '-';
            return status === 1 ? '启用' : '禁用';
        };

        const getStrategyStatusClass = (status) => {
            if (status === undefined || status === null) return '';
            return status === 1 ? 'status-enabled' : 'status-disabled';
        };

        const closeStrategyModal = () => {
            showAddStrategyModal.value = false;
            showEditStrategyModal.value = false;
            Object.assign(strategyForm, {
                id: null, name: '', description: '', pricingModel: '',
                firstWeightKg: null, firstWeightFee: null,
                additionalWeightKg: null, additionalWeightFee: null,
                volumetricWeightRatio: null, status: 1
            });
        };

        // 级联选择器相关方法
        const toggleProvinceSelection = (province) => {
            // 强化数据验证和错误提示
            if (!province) {
                console.error('無效的省份数据: undefined');
                return;
            }

            // 强化ID字段的获取逻辑，兼容id和areaId字段
            const provinceId = province.id || province.areaId;
            if (!provinceId) {
                console.error('無效的省份 ID，缺少id或areaId字段:', province);
                return;
            }

            // 检查children字段
            if (!province.children) {
                // 如果没有children字段，尝试在数据源中查找完整的省份对象
                const fullProvince = (areaTree.value || []).find(p => (p.id === provinceId || p.areaId === provinceId));
                if (fullProvince && fullProvince.children) {
                    // 如果找到完整的省份对象，使用它代替原来的省份对象
                    province = fullProvince;
                } else {
                    console.warn('省份对象缺少children字段，且无法找到完整对象:', province);
                    // 不带children的情况下，只切换当前省份的选中状态
                    const isSelected = cascaderState.selectedProvinces.has(provinceId);

                    if (isSelected) {
                        cascaderState.selectedProvinces.delete(provinceId);
                        console.log('取消选择省份:', province.name || province.provinceName);
                    } else {
                        cascaderState.selectedProvinces.add(provinceId);
                        console.log('选择省份:', province.name || province.provinceName);
                    }

                    // 更新表单数据
                    updateSelectedAreaIds();
                    return;
                }
            }

            const isSelected = cascaderState.selectedProvinces.has(provinceId);

            // 获取联动状态
            const linkageEnabled = cascaderState.isLinkageEnabled === true; // 只有明确启用时才联动

            console.log(`🔗 [省份选择] ${province.name}, 联动状态:`, {
                linkageEnabled,
                rawValue: cascaderState.isLinkageEnabled,
                isSelected,
                hasChildren: province.children?.length || 0
            });

            if (isSelected) {
                // 取消选择省份
                cascaderState.selectedProvinces.delete(provinceId);

                // 如果启用了联动，同时级联取消所有子级选择
                if (linkageEnabled) {
                    province.children.forEach(city => {
                        if (city) {
                            const cityId = city.id || city.areaId;
                            if (cityId) {
                                cascaderState.selectedCities.delete(cityId);
                                if (city.children) {
                                    city.children.forEach(district => {
                                        if (district) {
                                            const districtId = district.id || district.areaId;
                                            if (districtId) {
                                                cascaderState.selectedDistricts.delete(districtId);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                    console.log('取消选择省份，联动取消其下所有城市和区县:', province.name || province.provinceName);
                } else {
                    console.log('取消选择省份（联动已禁用）:', province.name || province.provinceName);
                }
            } else {
                // 选择省份
                cascaderState.selectedProvinces.add(provinceId);

                // 如果启用了联动，同时级联选择所有子级
                if (linkageEnabled) {
                    province.children.forEach(city => {
                        if (city) {
                            const cityId = city.id || city.areaId;
                            if (cityId) {
                                cascaderState.selectedCities.add(cityId);
                                if (city.children) {
                                    city.children.forEach(district => {
                                        if (district) {
                                            const districtId = district.id || district.areaId;
                                            if (districtId) {
                                                cascaderState.selectedDistricts.add(districtId);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                    console.log('选择省份，联动选择其下所有城市和区县:', province.name || province.provinceName);
                } else {
                    console.log('选择省份（联动已禁用）:', province.name || province.provinceName);
                }
            }

            // 更新表单数据
            updateSelectedAreaIds();
        };

        const toggleCitySelection = (city, province) => {
            if (!city || !city.id || !city.children || !province) {
                console.error('无效的城市或省份数据:', city, province);
                return;
            }

            const isSelected = cascaderState.selectedCities.has(city.id);

            // 检查当前城市是否为半选中状态
            const isIndeterminate = isCityIndeterminate(city);

            // 获取联动状态
            const linkageEnabled = cascaderState.isLinkageEnabled === true; // 只有明确启用时才联动

            console.log(`城市选择切换: ${city.name}, 当前选中: ${isSelected}, 半选中: ${isIndeterminate}, 联动: ${linkageEnabled}`);

            if (isSelected && !isIndeterminate) {
                // 城市已完全选中，执行取消全选
                console.log(`取消选择城市: ${city.name}`);
                cascaderState.selectedCities.delete(city.id);

                // 如果启用了联动，取消选择所有子级区县
                if (linkageEnabled) {
                    city.children.forEach(district => {
                        if (district && district.id) {
                            cascaderState.selectedDistricts.delete(district.id);
                        }
                    });
                }

                // 检查省份状态：只有在省份下既没有选中的城市，也没有选中的区县时，才取消省份选择
                if (linkageEnabled) {
                    const hasSelectedCityInProvince = province.children.some(c =>
                        c && c.id && cascaderState.selectedCities.has(c.id)
                    );

                    // 检查省份下是否还有选中的区县
                    const hasSelectedDistrictInProvince = province.children.some(c =>
                        c && c.children && c.children.some(d =>
                            d && d.id && cascaderState.selectedDistricts.has(d.id)
                        )
                    );

                    // 只有在省份下既没有选中的城市，也没有选中的区县时，才取消省份选择
                    if (!hasSelectedCityInProvince && !hasSelectedDistrictInProvince) {
                        cascaderState.selectedProvinces.delete(province.id);
                        console.log('省份下没有任何选中项，取消省份选择:', province.name);
                    } else {
                        console.log('省份下还有其他选中项，保持省份选择:', province.name);
                    }
                }
            } else {
                // 城市未选中或半选中，执行全选
                console.log(`选择城市: ${city.name}`);
                cascaderState.selectedCities.add(city.id);

                // 如果启用了联动，选择所有子级区县
                if (linkageEnabled) {
                    city.children.forEach(district => {
                        if (district && district.id) {
                            cascaderState.selectedDistricts.add(district.id);
                        }
                    });

                    // 检查省份状态：如果该省份下所有城市都被选中，则自动选择省份
                    const allCitiesSelected = province.children.every(c =>
                        !c || !c.id || cascaderState.selectedCities.has(c.id)
                    );
                    if (allCitiesSelected) {
                        cascaderState.selectedProvinces.add(province.id);
                    }
                }
            }

            // 更新表单数据
            updateSelectedAreaIds();
            console.log('城市选择完成，已选区域数量:', batchMappingForm.areaIds.length);
        };

        const toggleDistrictSelection = (district, city, province) => {
            if (!district || !district.id || !city || !province) {
                console.error('无效的区县、城市或省份数据:', district, city, province);
                return;
            }

            const isSelected = cascaderState.selectedDistricts.has(district.id);

            // 获取联动状态
            const linkageEnabled = cascaderState.isLinkageEnabled === true; // 只有明确启用时才联动

            if (isSelected) {
                cascaderState.selectedDistricts.delete(district.id);
                console.log('取消选择区县:', district.name);
            } else {
                cascaderState.selectedDistricts.add(district.id);
                console.log('选择区县:', district.name);
            }

            // 如果启用了联动，检查和更新父级状态
            if (linkageEnabled) {
                // 检查城市状态：如果该城市下没有选中的区县，则取消城市选择
                const hasSelectedDistrictInCity = city.children.some(d =>
                    d && d.id && cascaderState.selectedDistricts.has(d.id)
                );
                if (!hasSelectedDistrictInCity) {
                    cascaderState.selectedCities.delete(city.id);
                } else if (city.children.every(d => !d || !d.id || cascaderState.selectedDistricts.has(d.id))) {
                    // 如果该城市下所有区县都被选中，则自动选择城市
                    cascaderState.selectedCities.add(city.id);
                }

                // 检查省份状态：只有在省份下既没有选中的城市，也没有选中的区县时，才取消省份选择
                const hasSelectedCityInProvince = province.children.some(c =>
                    c && c.id && cascaderState.selectedCities.has(c.id)
                );

                const hasSelectedDistrictInProvince = province.children.some(c =>
                    c && c.children && c.children.some(d =>
                        d && d.id && cascaderState.selectedDistricts.has(d.id)
                    )
                );

                if (!hasSelectedCityInProvince && !hasSelectedDistrictInProvince) {
                    cascaderState.selectedProvinces.delete(province.id);
                    console.log('省份下没有任何选中项，取消省份选择:', province.name);
                } else if (province.children.every(c => !c || !c.id || cascaderState.selectedCities.has(c.id))) {
                    // 如果该省份下所有城市都被选中，则自动选择省份
                    cascaderState.selectedProvinces.add(province.id);
                }
            }

            // 更新表单数据
            updateSelectedAreaIds();
        };

        // 更新选中的区域 ID 列表
        const updateSelectedAreaIds = () => {
            const selectedIds = [];

            // 添加选中的省份
            cascaderState.selectedProvinces.forEach(id => selectedIds.push(id));

            // 添加选中的城市
            cascaderState.selectedCities.forEach(id => selectedIds.push(id));

            // 添加选中的区县
            cascaderState.selectedDistricts.forEach(id => selectedIds.push(id));

            batchMappingForm.areaIds = selectedIds;
            mappingForm.areaId = selectedIds.length > 0 ? selectedIds[0] : '';

            console.log('更新选中区域 ID:', selectedIds);
        };

        const toggleProvinceExpansion = (province) => {
            if (!province || !province.id) {
                console.error('无效的省份数据:', province);
                return;
            }
            if (cascaderState.expandedProvinces.has(province.id)) {
                cascaderState.expandedProvinces.delete(province.id);
            } else {
                cascaderState.expandedProvinces.add(province.id);
            }
            console.log('切换省份展开状态:', province.name);
        };

        const toggleCityExpansion = (city) => {
            if (!city || !city.id) {
                console.error('无效的城市数据:', city);
                return;
            }
            if (cascaderState.expandedCities.has(city.id)) {
                cascaderState.expandedCities.delete(city.id);
            } else {
                cascaderState.expandedCities.add(city.id);
            }
            console.log('切换城市展开状态:', city.name);
        };

        const isProvinceIndeterminate = (province) => {
            if (!province || !province.children || province.children.length === 0) {
                return false;
            }

            // 检查省份是否已选中
            const provinceId = province.id || province.areaId;
            const isProvinceSelected = cascaderState.selectedProvinces.has(provinceId);

            // 统计选中的城市数量
            const selectedCityCount = province.children.filter(city =>
                city && (city.id || city.areaId) && cascaderState.selectedCities.has(city.id || city.areaId)
            ).length;

            // 统计选中的区县数量
            let selectedDistrictCount = 0;
            let totalDistrictCount = 0;
            province.children.forEach(city => {
                if (city && city.children) {
                    totalDistrictCount += city.children.length;
                    selectedDistrictCount += city.children.filter(district =>
                        district && (district.id || district.areaId) && cascaderState.selectedDistricts.has(district.id || district.areaId)
                    ).length;
                }
            });

            // 如果省份已选中且所有城市都选中，则不是半选中
            if (isProvinceSelected && selectedCityCount === province.children.length && selectedDistrictCount === totalDistrictCount) {
                return false;
            }

            // 如果有部分城市选中或部分区县选中，则为半选中
            const hasPartialSelection = selectedCityCount > 0 || selectedDistrictCount > 0;
            const hasFullSelection = selectedCityCount === province.children.length && selectedDistrictCount === totalDistrictCount;

            return hasPartialSelection && !hasFullSelection;
        };

        const isCityIndeterminate = (city) => {
            if (!city || !city.children || city.children.length === 0) {
                return false;
            }

            // 检查城市是否已选中
            const cityId = city.id || city.areaId;
            const isCitySelected = cascaderState.selectedCities.has(cityId);

            // 统计选中的区县数量
            const selectedDistrictCount = city.children.filter(district =>
                district && (district.id || district.areaId) && cascaderState.selectedDistricts.has(district.id || district.areaId)
            ).length;

            // 如果城市已选中且所有区县都选中，则不是半选中
            if (isCitySelected && selectedDistrictCount === city.children.length) {
                return false;
            }

            // 如果有部分区县选中，则为半选中
            const hasPartialSelection = selectedDistrictCount > 0;
            const hasFullSelection = selectedDistrictCount === city.children.length;

            return hasPartialSelection && !hasFullSelection;
        };

        // 联动功能相关方法
        const toggleLinkage = () => {
            cascaderState.isLinkageEnabled = !cascaderState.isLinkageEnabled;
            console.log('🔗 联动状态切换:', cascaderState.isLinkageEnabled ? '已启用' : '已禁用');
        };

        // 全选功能方法
        const toggleSelectAllProvinces = () => {
            const allSelected = (areaTree.value || []).every(province =>
                cascaderState.selectedProvinces.has(province.id)
            );

            if (allSelected) {
                // 取消全选
                (areaTree.value || []).forEach(province => {
                    cascaderState.selectedProvinces.delete(province.id);
                });
            } else {
                // 全选
                (areaTree.value || []).forEach(province => {
                    cascaderState.selectedProvinces.add(province.id);
                });
            }
            updateSelectedAreaIds();
        };

        const toggleSelectAllCities = () => {
            const expandedProvinces = (areaTree.value || []).filter(province =>
                cascaderState.expandedProvinces.has(province.id)
            );

            const allExpandedCities = [];
            expandedProvinces.forEach(province => {
                if (province.children) {
                    allExpandedCities.push(...province.children);
                }
            });

            const allSelected = allExpandedCities.every(city =>
                cascaderState.selectedCities.has(city.id)
            );

            if (allSelected) {
                // 取消全选
                allExpandedCities.forEach(city => {
                    cascaderState.selectedCities.delete(city.id);
                });
            } else {
                // 全选
                allExpandedCities.forEach(city => {
                    cascaderState.selectedCities.add(city.id);
                });
            }
            updateSelectedAreaIds();
        };

        const toggleSelectAllDistricts = () => {
            const allExpandedDistricts = [];
            (areaTree.value || []).forEach(province => {
                if (province.children) {
                    province.children.forEach(city => {
                        if (cascaderState.expandedCities.has(city.id) && city.children) {
                            allExpandedDistricts.push(...city.children);
                        }
                    });
                }
            });

            const allSelected = allExpandedDistricts.every(district =>
                cascaderState.selectedDistricts.has(district.id)
            );

            if (allSelected) {
                // 取消全选
                allExpandedDistricts.forEach(district => {
                    cascaderState.selectedDistricts.delete(district.id);
                });
            } else {
                // 全选
                allExpandedDistricts.forEach(district => {
                    cascaderState.selectedDistricts.add(district.id);
                });
            }
            updateSelectedAreaIds();
        };

        const isAllProvincesSelected = () => {
            return (areaTree.value || []).length > 0 && (areaTree.value || []).every(province =>
                cascaderState.selectedProvinces.has(province.id)
            );
        };

        const isAllExpandedCitiesSelected = () => {
            const expandedProvinces = (areaTree.value || []).filter(province =>
                cascaderState.expandedProvinces.has(province.id)
            );

            if (expandedProvinces.length === 0) return false;

            const allExpandedCities = [];
            expandedProvinces.forEach(province => {
                if (province.children) {
                    allExpandedCities.push(...province.children);
                }
            });

            return allExpandedCities.length > 0 && allExpandedCities.every(city =>
                cascaderState.selectedCities.has(city.id)
            );
        };

        const isAllExpandedDistrictsSelected = () => {
            const allExpandedDistricts = [];
            (areaTree.value || []).forEach(province => {
                if (province.children) {
                    province.children.forEach(city => {
                        if (cascaderState.expandedCities.has(city.id) && city.children) {
                            allExpandedDistricts.push(...city.children);
                        }
                    });
                }
            });

            return allExpandedDistricts.length > 0 && allExpandedDistricts.every(district =>
                cascaderState.selectedDistricts.has(district.id)
            );
        };

        const clearAllSelections = () => {
            cascaderState.selectedProvinces.clear();
            cascaderState.selectedCities.clear();
            cascaderState.selectedDistricts.clear();
            updateSelectedAreaIds();
        };



        // 查询方法定义
        const searchAssignments = async () => {
            try {
                console.log('执行分配查询，查询条件:', assignmentQuery);

                // 调用API进行查询
                const result = await api.getAssignments(assignmentQuery);

                if (result.code === 0) {
                    assignments.value = result.data || [];

                    // 为分配填充策略名称
                    (assignments.value || []).forEach(assignment => {
                        const strategy = (strategies.value || []).find(s => s.id === assignment.strategyId);
                        assignment.strategyName = strategy ? strategy.name : '未知策略';
                    });

                    const resultCount = assignments.value.length;
                    console.log('分配查询完成，结果数量:', resultCount);

                    if (resultCount === 0) {
                        showMessage('查询成功，找到 0 条记录');
                    } else {
                        showMessage(`查询成功，找到 ${resultCount} 条记录`);
                    }
                } else {
                    assignments.value = [];
                    showMessage('查询失败: ' + result.msg, true);
                }
            } catch (err) {
                console.error('分配查询失败:', err);
                assignments.value = [];
                showMessage('查询失败', true);
            }
        };

        const resetAssignmentQuery = async () => {
            Object.assign(assignmentQuery, {
                warehouseCode: '',
                logisticsCompanyCode: '',
                strategyName: '',
                status: ''
            });
            console.log('重置分配查询条件，重新加载所有数据');
            await loadAssignments();
            showMessage('已重置查询条件');
        };

        // 重新构建映射显示数据的辅助函数
        const rebuildMappingDisplay = async (strategyMappings) => {
            try {
                // 获取重量规则数据
                const weightRulesResult = await api.getWeightRules(selectedMappingStrategyId.value);
                const weightRules = weightRulesResult.code === 0 ? (weightRulesResult.data || []) : [];

                // 获取所有区域数据
                const allAreas = areas.value || [];

                // 按重量规则分组映射
                const ruleGroupedMappings = new Map();

                strategyMappings.forEach(mapping => {
                    const ruleId = mapping.segmentRuleId;
                    if (!ruleGroupedMappings.has(ruleId)) {
                        ruleGroupedMappings.set(ruleId, {
                            ruleId: ruleId,
                            areas: [],
                            areasDisplay: []
                        });
                    }

                    const group = ruleGroupedMappings.get(ruleId);

                    // 查找区域信息
                    const areaInfo = allAreas.find(area => area.id === mapping.areaId);
                    if (areaInfo) {
                        const areaName = formatAreaName(areaInfo);
                        group.areas.push(areaName);
                        group.areasDisplay.push(areaName);
                    }
                });

                // 构建最终显示数据
                const mergedMappings = [];
                ruleGroupedMappings.forEach((group, ruleId) => {
                    // 查找对应的重量规则信息
                    const rule = weightRules.find(r => r.id === ruleId);
                    if (rule && group.areas.length > 0) {
                        mergedMappings.push({
                            ruleId: ruleId,
                            upperBound: rule.upperBound,
                            freight: rule.freight,
                            areas: group.areas,
                            areasDisplay: group.areasDisplay
                        });
                    }
                });

                mappingMergedData.value = mergedMappings;
                console.log('映射显示数据重新构建完成:', mergedMappings.length, '条');

            } catch (err) {
                console.error('重新构建映射显示数据失败:', err);
                mappingMergedData.value = [];
            }
        };

        const searchMappings = async () => {
            try {
                console.log('执行映射查询，查询条件:', mappingQuery, '选中策略:', selectedMappingStrategyId.value);

                if (!selectedMappingStrategyId.value) {
                    showMessage('请先选择策略', true);
                    return;
                }

                // 构建后端API查询参数，传递给后端进行过滤
                const mappingQueryParams = {
                    strategyId: selectedMappingStrategyId.value
                };

                console.log('使用后端查询参数加载映射数据:', mappingQueryParams);
                const mappingsResult = await api.getMappings(mappingQueryParams);

                if (mappingsResult.code === 0) {
                    let strategyMappings = mappingsResult.data || [];
                    console.log('映射数据加载成功:', strategyMappings.length, '条');

                    // 如果有区域名称搜索，在前端进行过滤
                    if (mappingQuery.areaName && mappingQuery.areaName.trim()) {
                        const searchKeyword = mappingQuery.areaName.toLowerCase();
                        console.log('在前端过滤区域名称:', searchKeyword);

                        // 获取所有区域数据用于名称匹配
                        const allAreas = areas.value || [];

                        strategyMappings = strategyMappings.filter(mapping => {
                            // 通过区域ID查找区域名称
                            const areaInfo = allAreas.find(area => area.id === mapping.areaId);
                            if (areaInfo) {
                                const areaName = formatAreaName(areaInfo);
                                return areaName && areaName.toLowerCase().includes(searchKeyword);
                            }
                            return false;
                        });

                        console.log('区域名称过滤后的映射数据:', strategyMappings.length, '条');
                    }

                    // 重新构建映射合并数据用于显示
                    await rebuildMappingDisplay(strategyMappings);
                } else {
                    console.error('映射数据查询失败:', mappingsResult.msg);
                    mappingMergedData.value = [];
                }

                const totalResults = mappingMergedData.value?.length || 0;
                showMessage(`查询完成，找到 ${totalResults} 条结果`);
            } catch (err) {
                console.error('映射查询失败:', err);
                showMessage('查询失败', true);
            }
        };

        const resetMappingQuery = async () => {
            Object.assign(mappingQuery, {
                areaName: ''
            });
            console.log('重置映射查询条件，重新加载数据');
            if (selectedMappingStrategyId.value) {
                await loadMappingDetails();
            }
            showMessage('已重置查询条件');
        };

        // 区域管理页面的分页搜索方法
        const searchAreasWithPage = async () => {
            try {
                console.log('执行区域分页查询，查询条件:', areaQuery);

                // 重置到第一页
                areaPagination.currentPage = 1;

                // 调用分页加载方法
                await loadAreasWithPage();

                const resultCount = areas.value.length;
                const totalCount = areaPagination.totalItems;
                console.log('区域分页查询完成，当前页结果数量:', resultCount, '总记录数:', totalCount);

                if (totalCount === 0) {
                    showMessage('查询成功，找到 0 条记录');
                } else {
                    showMessage(`查询成功，找到 ${totalCount} 条记录`);
                }
            } catch (err) {
                console.error('区域分页查询失败:', err);
                areas.value = [];
                areaPagination.totalItems = 0;
                areaPagination.totalPages = 0;
                showMessage('查询失败', true);
            }
        };

        // 其他页面的区域搜索方法（运费计算等）
        const searchAreas = async () => {
            try {
                console.log('执行区域查询，查询条件:', areaQuery);

                // 调用API进行查询
                const result = await api.getAreas(areaQuery);

                if (result.code === 0) {
                    areas.value = result.data || [];

                    const resultCount = areas.value.length;
                    console.log('区域查询完成，结果数量:', resultCount);

                    if (resultCount === 0) {
                        showMessage('查询成功，找到 0 条记录');
                    } else {
                        showMessage(`查询成功，找到 ${resultCount} 条记录`);
                    }

                    // 重新构建区域树
                    buildAreaTree();
                } else {
                    areas.value = [];
                    showMessage('查询失败: ' + result.msg, true);
                }
            } catch (err) {
                console.error('区域查询失败:', err);
                areas.value = [];
                showMessage('查询失败', true);
            }
        };

        const resetAreaQuery = async () => {
            Object.assign(areaQuery, {
                level: '',
                provinceName: '',
                cityName: '',
                districtName: ''
            });
            console.log('重置区域查询条件，重新加载所有数据');
            await loadAreasWithPage();
            showMessage('已重置查询条件');
        };

        const selectAssignment = (assignment) => {
            if (!assignment || !assignment.id) {
                console.error('无效的分配数据:', assignment);
                return;
            }
            selectedAssignment.value = assignment.id;
            selectedMappingStrategyId.value = assignment.strategyId;
            console.log('选择分配:', assignment);
            loadMappingDetails();
        };

        // 从策略列表中选择策略
        const selectStrategyFromList = (strategy) => {
            if (!strategy || !strategy.id) {
                console.error('无效的策略数据:', strategy);
                return;
            }
            selectedMappingStrategyId.value = strategy.id;
            console.log('从策略列表选择策略:', strategy);
            loadMappingDetails();
        };

        const getDisplayAssignments = () => {
            return assignments.value || [];
        };

        // 新增：获取所有重量规则（去重）
        const getAllWeightRules = () => {
            const allRules = new Map();

            // 从按区域分组的数据中收集所有重量规则
            mappingGroupByAreaData.value.forEach(areaGroup => {
                if (areaGroup.weightRules) {
                    areaGroup.weightRules.forEach(rule => {
                        if (!allRules.has(rule.ruleId)) {
                            allRules.set(rule.ruleId, {
                                id: rule.ruleId,
                                upperBound: rule.upperBound,
                                freight: rule.freight
                            });
                        }
                    });
                }
            });

            // 按重量上限排序
            return Array.from(allRules.values()).sort((a, b) => a.upperBound - b.upperBound);
        };

        // 新增：格式化重量范围显示
        const formatWeightRange = (weightRule, index) => {
            const allRules = getAllWeightRules();
            if (index === 0) {
                return `0.0000 - ≤重量≤ - ${weightRule.upperBound}`;
            }
            const prevRule = allRules[index - 1];
            return `${prevRule.upperBound} - ≤重量≤ - ${weightRule.upperBound}`;
        };

        // 新增：获取首重费用（从第一个区域的配置中获取）
        const getFirstWeightFee = (weightRule) => {
            const firstAreaGroup = mappingGroupByAreaData.value[0];
            return firstAreaGroup ? (firstAreaGroup.firstWeightFee || '1.6000') : '1.6000';
        };

        // 新增：获取续重重量
        const getAdditionalWeight = (weightRule) => {
            const firstAreaGroup = mappingGroupByAreaData.value[0];
            return firstAreaGroup ? (firstAreaGroup.additionalWeightKg || '0.0000') : '0.0000';
        };

        // 新增：获取续重费用
        const getAdditionalFee = (weightRule) => {
            const firstAreaGroup = mappingGroupByAreaData.value[0];
            return firstAreaGroup ? (firstAreaGroup.additionalWeightFee || '0.0000') : '0.0000';
        };

        // 计算属性：所有重量规则
        const allWeightRules = computed(() => {
            return getAllWeightRules();
        });

        const deleteMappingRuleForAreas = async (areas, ruleId) => {
            const areaCount = areas.length;
            if (!areas || !ruleId) {
                showMessage('无效的删除参数', true);
                return;
            }
            if (!confirm(`确定要删除这${areaCount}个区域的映射规则吗？`)) return;

            try {
                // 查找要删除的映射ID列表
                console.log('🔍 查找要删除的映射ID列表...');
                const mappingData = await api.getMappings({ strategyId: selectedMappingStrategyId.value });
                if (mappingData.code !== 0) {
                    showMessage('获取映射数据失败', true);
                    return;
                }

                const allMappings = mappingData.data || [];
                const allAreas = areas.value || [];

                // 收集所有要删除的映射ID
                const mappingIdsToDelete = [];
                const errors = [];

                console.log('删除映射规则 - 输入参数:', { areas, ruleId, allAreasCount: allAreas.length });

                for (const areaIdentifier of areas) {
                    let areaInfo = null;

                    // 智能类型判断（修复后的逻辑）
                    if (typeof areaIdentifier === 'string') {
                        if (areaIdentifier.startsWith('区域ID:')) {
                            // 处理 "区域ID:123" 格式
                            const areaId = parseInt(areaIdentifier.replace('区域ID:', ''));
                            areaInfo = allAreas.find(area => area.id === areaId);
                            console.log(`解析区域ID格式: ${areaIdentifier} -> ${areaId}, 找到区域:`, areaInfo);
                        } else {
                            // 处理区域名称
                            areaInfo = allAreas.find(area => formatAreaName(area) === areaIdentifier);
                            console.log(`按区域名称查找: ${areaIdentifier}, 找到区域:`, areaInfo);
                        }
                    } else if (typeof areaIdentifier === 'number') {
                        // 处理直接传递的数字ID
                        areaInfo = allAreas.find(area => area.id === areaIdentifier);
                        console.log(`按数字ID查找: ${areaIdentifier}, 找到区域:`, areaInfo);
                    } else if (typeof areaIdentifier === 'object' && areaIdentifier !== null) {
                        // 处理AreaInfo对象类型
                        if (areaIdentifier.areaId) {
                            // 从AreaInfo对象中提取areaId
                            areaInfo = allAreas.find(area => area.id === areaIdentifier.areaId);
                            console.log(`从AreaInfo对象提取区域ID: ${areaIdentifier.areaId}, 找到区域:`, areaInfo);
                        } else if (areaIdentifier.areaName) {
                            // 从AreaInfo对象中提取areaName
                            areaInfo = allAreas.find(area => formatAreaName(area) === areaIdentifier.areaName);
                            console.log(`从AreaInfo对象提取区域名称: ${areaIdentifier.areaName}, 找到区域:`, areaInfo);
                        }
                    }

                    if (!areaInfo) {
                        const errorMsg = `未找到区域：${areaIdentifier}`;
                        errors.push(errorMsg);
                        console.error(errorMsg, { areaIdentifier, type: typeof areaIdentifier });
                        continue;
                    }

                    // 查找对应的映射记录
                    const mapping = allMappings.find(m =>
                        m.areaId === areaInfo.id &&
                        m.segmentRuleId === ruleId &&
                        m.strategyId === selectedMappingStrategyId.value
                    );

                    if (!mapping) {
                        const areaName = formatAreaName(areaInfo);
                        const errorMsg = `未找到${areaName}的映射记录 (区域ID:${areaInfo.id}, 规则ID:${ruleId})`;
                        errors.push(errorMsg);
                        console.error(errorMsg);
                        continue;
                    }

                    mappingIdsToDelete.push(mapping.id);
                }

                if (mappingIdsToDelete.length === 0) {
                    showMessage('没有找到要删除的映射记录', true);
                    if (errors.length > 0) {
                        console.error('删除错误详情:', errors);
                        showMessage(`删除失败：${errors.join('；')}`, true);
                    }
                    return;
                }

                // 使用批量删除接口
                console.log('🗑️ 批量删除映射，ID列表:', mappingIdsToDelete);
                const result = await api.batchDeleteMappings(mappingIdsToDelete);

                if (result.code === 0) {
                    const deleteCount = result.data;
                    showMessage(`成功删除${deleteCount}个映射`);
                    // 重新加载映射数据
                    await loadMappingDetails();
                } else {
                    showMessage(result.msg || '批量删除失败', true);
                }

                if (errors.length > 0) {
                    console.error('删除错误详情:', errors);
                    showMessage(`部分删除失败：${errors.join('；')}`, true);
                }
            } catch (err) {
                console.error('删除映射规则失败:', err);
                showMessage(err.message, true);
            }
        };

        const getAssignmentStatusClass = (status) => {
            if (status === undefined || status === null) return '';
            return status === 1 ? 'status-enabled' : 'status-disabled';
        };

        const getAssignmentStatusText = (status) => {
            if (status === undefined || status === null) return '-';
            return status === 1 ? '启用' : '禁用';
        };

        const toggleAssignmentStatus = async (assignment) => {
            if (!assignment || !assignment.id) {
                showMessage('无效的分配数据', true);
                return;
            }

            const newStatus = assignment.status === 1 ? 2 : 1;
            const statusText = newStatus === 1 ? '启用' : '禁用';

            if (!confirm(`确定要${statusText}这个分配吗？`)) return;

            try {
                const result = await api.updateAssignmentStatus({
                    id: assignment.id,
                    status: newStatus
                });
                if (result.code === 0) {
                    showMessage(`${statusText}成功`);
                    await loadAssignments();
                } else {
                    showMessage(result.msg || `${statusText}失败`, true);
                }
            } catch (err) {
                showMessage(err.message, true);
            }
        };

        // 区域管理相关方法
        const addArea = () => {
            console.log('打开新增区域模态框');
            showAddAreaModal.value = true;
        };

        const editArea = (area) => {
            if (!area) {
                showMessage('无效的区域数据', true);
                return;
            }
            console.log('编辑区域:', area);
            Object.assign(areaForm, area);
            showEditAreaModal.value = true;
        };

        const submitArea = async () => {
            try {
                console.log('提交区域数据:', areaForm);

                // 数据验证
                if (!areaForm.level || !areaForm.provinceName) {
                    showMessage('请填写必要信息', true);
                    return;
                }

                submitting.value = true;

                const apiMethod = areaForm.areaId ? 'updateArea' : 'addArea';
                const result = await api[apiMethod](areaForm);

                if (result.code === 0) {
                    showMessage('操作成功');
                    closeAreaModal();
                    await loadAreasWithPage();
                } else {
                    showMessage(result.msg || '操作失败', true);
                }
            } catch (err) {
                console.error('区域提交失败:', err);
                showMessage(err.message || '提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        const closeAreaModal = () => {
            showAddAreaModal.value = false;
            showEditAreaModal.value = false;
            // 重置表单
            Object.assign(areaForm, {
                areaId: null,
                provinceCode: '',
                provinceName: '',
                provinceShortName: '',
                cityCode: '',
                cityName: '',
                cityShortName: '',
                districtCode: '',
                districtName: '',
                districtShortName: '',
                level: ''
            });
        };

        const onLevelChange = () => {
            const level = parseInt(areaForm.level);

            // 当层级小于2时清除城市字段
            if (level < 2) {
                areaForm.cityCode = '';
                areaForm.cityName = '';
                areaForm.cityShortName = '';
            }

            // 当层级不等于3时清除区县字段
            if (level !== 3) {
                areaForm.districtCode = '';
                areaForm.districtName = '';
                areaForm.districtShortName = '';
            }
        };

        const getAreaLevelName = (level) => {
            const levelMap = {
                1: '省级',
                2: '市级',
                3: '区县级'
            };
            return levelMap[level] || '未知';
        };

        const deleteArea = async (id) => {
            if (!id) {
                showMessage('无效的区域ID', true);
                return;
            }
            if (!confirm('确定要删除这个区域吗？')) return;

            try {
                const result = await api.deleteArea({ areaId: id });
                if (result.code === 0) {
                    showMessage('删除成功');
                    await loadAreasWithPage();
                } else {
                    showMessage(result.msg || '删除失败', true);
                }
            } catch (err) {
                showMessage(err.message, true);
            }
        };

        // 导出区域数据功能 - 后端导出
        const exportAreas = async () => {
            try {
                console.log('开始导出区域数据...');

                // 构建导出参数（使用当前查询条件）
                const exportParams = {
                    ...areaQuery
                };

                console.log('导出参数:', exportParams);
                showMessage('正在导出，请稍候...');

                // 使用统一API服务导出数据
                const response = await api.exportAreas(exportParams);

                // 获取文件名（从响应头中获取或使用默认名称）
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = '区域数据.xlsx';

                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                    if (filenameMatch) {
                        filename = filenameMatch[1];
                    }
                }

                // 处理文件下载
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.style.display = 'none';

                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // 清理内存
                window.URL.revokeObjectURL(url);

                showMessage('导出成功');

            } catch (err) {
                console.error('导出区域数据失败:', err);
                showMessage('导出失败: ' + err.message, true);
            }
        };

        // 分页控制方法
        const goToPage = (page) => {
            if (page < 1 || page > areaPagination.totalPages) return;
            areaPagination.currentPage = page;
            loadAreasWithPage();
        };

        const previousPage = () => {
            if (areaPagination.currentPage > 1) {
                areaPagination.currentPage--;
                loadAreasWithPage();
            }
        };

        const nextPage = () => {
            if (areaPagination.currentPage < areaPagination.totalPages) {
                areaPagination.currentPage++;
                loadAreasWithPage();
            }
        };

        const changePageSize = (newSize) => {
            areaPagination.pageSize = newSize;
            areaPagination.currentPage = 1; // 重置到第一页
            loadAreasWithPage();
        };

        // 生成智能页码数组
        const getPageNumbers = () => {
            const current = areaPagination.currentPage;
            const total = areaPagination.totalPages;
            const pages = [];

            if (total <= 7) {
                // 总页数少于等于7页，显示所有页码
                for (let i = 1; i <= total; i++) {
                    pages.push(i);
                }
            } else {
                // 总页数大于7页，使用智能显示逻辑
                if (current <= 4) {
                    // 当前页在前面，显示 1,2,3,4,5,...,last
                    for (let i = 1; i <= 5; i++) {
                        pages.push(i);
                    }
                    pages.push('...');
                    pages.push(total);
                } else if (current >= total - 3) {
                    // 当前页在后面，显示 1,...,last-4,last-3,last-2,last-1,last
                    pages.push(1);
                    pages.push('...');
                    for (let i = total - 4; i <= total; i++) {
                        pages.push(i);
                    }
                } else {
                    // 当前页在中间，显示 1,...,current-1,current,current+1,...,last
                    pages.push(1);
                    pages.push('...');
                    for (let i = current - 1; i <= current + 1; i++) {
                        pages.push(i);
                    }
                    pages.push('...');
                    pages.push(total);
                }
            }

            return pages;
        };

        // 编辑映射相关方法 - 使用专门的编辑映射模态框
        const editMappingRuleForAreas = async (areas, ruleId) => {
            if (!areas || !ruleId || !selectedMappingStrategyId.value) {
                showMessage('无效的编辑参数', true);
                return;
            }

            try {
                console.log('📄 开始编辑映射规则:', {
                    areas,
                    ruleId,
                    strategyId: selectedMappingStrategyId.value
                });

                // 设置编辑映射表单的策略ID和重量规则ID
                editMappingForm.strategyId = selectedMappingStrategyId.value;
                editMappingForm.ruleId = ruleId;

                // 修复：从AreaInfo对象数组中提取区域ID列表
                const originalAreaIds = areas.map(areaInfo => areaInfo.areaId);
                editMappingForm.originalAreas = originalAreaIds; // 保存原始区域ID列表

                // 获取重量规则信息用于显示
                try {
                    const weightRulesResult = await api.getWeightRules(selectedMappingStrategyId.value);
                    if (weightRulesResult.code === 0) {
                        const weightRules = weightRulesResult.data || [];
                        const currentRule = weightRules.find(rule => rule.id === ruleId);
                        if (currentRule) {
                            editMappingForm.upperBound = currentRule.upperBound;
                            editMappingForm.freight = currentRule.freight;
                            console.log('✅ 重量规则信息获取成功:', currentRule);
                        } else {
                            console.warn('⚠️ 未找到对应的重量规则:', ruleId);
                        }
                    } else {
                        console.error('❌ 获取重量规则失败:', weightRulesResult.msg);
                    }
                } catch (error) {
                    console.error('❌ 获取重量规则异常:', error);
                }

                // 设置批量映射表单的策略ID和重量规则
                batchMappingForm.strategyId = selectedMappingStrategyId.value;
                batchMappingForm.segmentRuleIds = [ruleId];

                // 修复：直接从传入的AreaInfo对象数组中提取区域ID
                const areaIds = areas.map(areaInfo => areaInfo.areaId);

                console.log('🔍 编辑映射回显数据:', {
                    inputAreasCount: areas.length,
                    extractedAreaIds: areaIds,
                    firstArea: areas[0]
                });

                // 确保全局区域数据已加载
                const allAreas = areas.value || [];
                if (allAreas.length === 0) {
                    console.warn('⚠️ 全局区域数据为空，尝试重新加载...');
                    try {
                        const areasResult = await api.getAreas();
                        if (areasResult.code === 0) {
                            areas.value = areasResult.data || [];
                            console.log('📊 重新加载后区域数据:', areas.value.length, '条');
                            // 重新构建区域树
                            buildAreaTree();
                        } else {
                            console.error('❌ 重新加载区域数据失败:', areasResult.msg);
                        }
                    } catch (error) {
                        console.error('❌ 重新加载区域数据异常:', error);
                    }
                }

                // 设置选中的区域IDs到editMappingForm
                editMappingForm.selectedAreaIds = areaIds;

                // 清空并重置区域选择状态
                cascaderState.selectedProvinces.clear();
                cascaderState.selectedCities.clear();
                cascaderState.selectedDistricts.clear();

                // 修复：使用传入的AreaInfo对象直接设置选中状态
                const provinceIds = new Set();
                const cityIds = new Set();
                const districtIds = new Set();
                const provincesToExpand = new Set();
                const citiesToExpand = new Set();

                // 使用全局区域数据创建父级关系映射
                const finalAreas = areas.value || [];
                const provinceMap = new Map();
                const cityMap = new Map();
                finalAreas.forEach(area => {
                    if (area.level === 1) {
                        provinceMap.set(area.provinceName, area);
                    } else if (area.level === 2) {
                        cityMap.set(`${area.provinceName}-${area.cityName}`, area);
                    }
                });

                // 直接从传入的AreaInfo对象中设置选中状态
                areas.forEach(areaInfo => {
                    const areaId = areaInfo.areaId;
                    const level = areaInfo.level;

                    if (level === 1) {
                        provinceIds.add(areaId);
                    } else if (level === 2) {
                        cityIds.add(areaId);
                        // 查找并展开父级省份
                        const parentProvince = provinceMap.get(areaInfo.provinceName);
                        if (parentProvince) {
                            provincesToExpand.add(parentProvince.id || parentProvince.areaId);
                        }
                    } else if (level === 3) {
                        districtIds.add(areaId);
                        // 查找并展开父级省份和城市
                        const parentProvince = provinceMap.get(areaInfo.provinceName);
                        const parentCity = cityMap.get(`${areaInfo.provinceName}-${areaInfo.cityName}`);
                        if (parentProvince) provincesToExpand.add(parentProvince.id || parentProvince.areaId);
                        if (parentCity) citiesToExpand.add(parentCity.id || parentCity.areaId);
                    }
                });

                // 批量设置选中状态
                provinceIds.forEach(id => cascaderState.selectedProvinces.add(id));
                cityIds.forEach(id => cascaderState.selectedCities.add(id));
                districtIds.forEach(id => cascaderState.selectedDistricts.add(id));
                provincesToExpand.forEach(id => cascaderState.expandedProvinces.add(id));
                citiesToExpand.forEach(id => cascaderState.expandedCities.add(id));

                console.log('✅ 编辑回显完成:', {
                    provinces: provinceIds.size,
                    cities: cityIds.size,
                    districts: districtIds.size,
                    totalSelected: areaIds.length
                });

                // 更新表单数据和构建区域树（如果需要）
                if (areaTree.value.length === 0) {
                    await buildAreaTree();
                }
                updateSelectedAreaIds();

                // 显示模态框
                showEditMappingModal.value = true;
                console.log('✅ 编辑模态框已打开');
            } catch (error) {
                console.error('编辑映射区域时发生错误:', error);
                showMessage('编辑映射区域失败，请检查日志', true);
            }
        };


        const submitStrategy = async () => {
            try {
                console.log('提交策略数据:', strategyForm);

                // 数据验证
                if (!strategyForm.name || !strategyForm.name.trim()) {
                    showMessage('请输入策略名称', true);
                    return;
                }

                submitting.value = true;

                const apiMethod = strategyForm.id ? 'updateStrategy' : 'addStrategy';
                const result = await api[apiMethod](strategyForm);

                if (result.code === 0) {
                    showMessage('操作成功');
                    closeStrategyModal();
                    await loadStrategies();
                } else {
                    showMessage(result.msg || '操作失败', true);
                }
            } catch (err) {
                console.error('策略提交失败:', err);
                showMessage(err.message || '提交失败', true);
            } finally {
                submitting.value = false;
            }
        };

        // 策略编辑相关方法（用于映射管理页面）
        const editSelectedStrategy = async () => {
            console.log('🔧 编辑当前选中的策略:', selectedMappingStrategyId.value);

            if (!selectedMappingStrategyId.value) {
                showMessage('请先选择一个策略', true);
                return;
            }

            try {
                // 从策略列表中找到当前策略
                const currentStrategy = strategies.value.find(s => s.id === selectedMappingStrategyId.value);
                if (!currentStrategy) {
                    showMessage('未找到策略信息', true);
                    return;
                }

                // 确保 weightRules 数组已初始化
                if (!mappingStrategyForm.weightRules) {
                    mappingStrategyForm.weightRules = [];
                }

                // 填充基本信息
                Object.assign(mappingStrategyForm, {
                    id: currentStrategy.id,
                    name: currentStrategy.name,
                    description: currentStrategy.description || '',
                    pricingModel: currentStrategy.pricingModel || '',
                    firstWeightKg: currentStrategy.firstWeightKg || null,
                    firstWeightFee: currentStrategy.firstWeightFee || null,
                    additionalWeightKg: currentStrategy.additionalWeightKg || null,
                    additionalWeightFee: currentStrategy.additionalWeightFee || null,
                    volumetricWeightRatio: currentStrategy.volumetricWeightRatio || null,
                    status: currentStrategy.status || 1,
                    weightRules: [] // 重新初始化重量规则数组
                });

                // 加载重量规则
                try {
                    const weightRulesResult = await api.getWeightRules(selectedMappingStrategyId.value);
                    if (weightRulesResult.code === 0) {
                        const weightRules = weightRulesResult.data || [];
                        // 将重量规则转换为编辑格式，仅包含重量上限和费用
                        mappingStrategyForm.weightRules = weightRules.map(rule => ({
                            id: rule.id || null,
                            upperBound: rule.upperBound || 1.0,
                            freight: rule.freight || 0 // 邮资字段
                        }));

                        // 如果没有重量规则，创建一个默认规则
                        if (mappingStrategyForm.weightRules.length === 0) {
                            mappingStrategyForm.weightRules.push({
                                id: null,
                                upperBound: 1.0,
                                freight: 0 // 邮资字段
                            });
                        }

                        console.log('✅ 重量规则加载成功:', mappingStrategyForm.weightRules.length, '条');
                    } else {
                        console.warn('重量规则加载失败:', weightRulesResult.msg);
                        // 创建默认规则
                        mappingStrategyForm.weightRules = [{
                            id: null,
                            upperBound: 1.0,
                            freight: 0 // 邮资字段
                        }];
                    }
                } catch (err) {
                    console.error('加载重量规则失败:', err);
                    // 创建默认规则
                    mappingStrategyForm.weightRules = [{
                        id: null,
                        upperBound: 1.0,
                        freight: 0 // 邮资字段
                    }];
                }

                console.log('✅ 策略编辑表单已初始化:', mappingStrategyForm);
                showMappingStrategyEditModal.value = true;

            } catch (err) {
                console.error('编辑策略失败:', err);
                showMessage('编辑策略失败: ' + err.message, true);
            }
        };

        const submitMappingStrategyEdit = async () => {
            console.log('🚀 提交策略编辑数据:', mappingStrategyForm);

            // 表单验证
            const validation = validateMappingStrategyForm();
            if (!validation.isValid) {
                showMessage(validation.errors[0], true);
                return;
            }

            submittingMappingStrategy.value = true;
            try {
                const result = await api.updateStrategy(mappingStrategyForm);

                if (result.code === 0) {
                    showMessage('策略更新成功');
                    closeMappingStrategyEditModal();
                    // 重新加载策略列表
                    await loadStrategies();
                    // 重新加载映射详情（以获取更新后的数据）
                    if (selectedMappingStrategyId.value) {
                        await loadMappingDetails();
                    }
                } else {
                    showMessage(result.msg || '策略更新失败', true);
                }
            } catch (err) {
                console.error('❗ 策略编辑失败:', err);
                showMessage(err.message || '策略编辑失败', true);
            } finally {
                submittingMappingStrategy.value = false;
            }
        };

        const closeMappingStrategyEditModal = () => {
            showMappingStrategyEditModal.value = false;
            resetMappingStrategyForm();
        };

        const resetMappingStrategyForm = () => {
            Object.assign(mappingStrategyForm, {
                id: null,
                name: '',
                description: '',
                pricingModel: '',
                firstWeightKg: null,
                firstWeightFee: null,
                additionalWeightKg: null,
                additionalWeightFee: null,
                volumetricWeightRatio: null,
                status: 1,
                selectedAreas: [], // 重置选中区域
                weightRules: [{
                    id: null,
                    upperBound: 1.0,
                    freight: 0 // 邮资字段
                }]
            });

            // 重置区域选择器状态
            mappingAreaState.selectedProvinces.clear();
            mappingAreaState.selectedCities.clear();
            mappingAreaState.selectedDistricts.clear();
            mappingAreaState.expandedProvinces.clear();
            mappingAreaState.expandedCities.clear();
        };

        // 添加策略编辑中的重量规则
        const addMappingStrategyWeightRule = () => {
            console.log('📦 添加新的策略编辑重量规则');

            // 确保 weightRules 数组存在
            if (!mappingStrategyForm.weightRules) {
                mappingStrategyForm.weightRules = [];
            }

            const lastRule = mappingStrategyForm.weightRules.length > 0 ?
                mappingStrategyForm.weightRules[mappingStrategyForm.weightRules.length - 1] : null;

            const newRule = {
                id: null,
                upperBound: lastRule && lastRule.upperBound ? (lastRule.upperBound + 1.0) : 1.0,
                freight: lastRule && lastRule.freight !== undefined ? lastRule.freight : 0 // 邮资字段
            };

            mappingStrategyForm.weightRules.push(newRule);
            console.log('✅ 新增策略编辑重量规则成功，当前规则数量:', mappingStrategyForm.weightRules.length);
        };

        // 删除策略编辑中的重量规则
        const removeMappingStrategyWeightRule = (index) => {
            console.log('🗑️ 删除策略编辑重量规则，索引:', index);
            if (mappingStrategyForm.weightRules.length <= 1) {
                showMessage('至少需要保留一条重量规则', true);
                return;
            }
            mappingStrategyForm.weightRules.splice(index, 1);
            console.log('✅ 删除策略编辑重量规则成功，剩余规则数量:', mappingStrategyForm.weightRules.length);
        };

        const validateMappingStrategyForm = () => {
            const errors = [];

            if (!mappingStrategyForm.name || !mappingStrategyForm.name.trim()) {
                errors.push('请输入策略名称');
            }

            if (!mappingStrategyForm.pricingModel) {
                errors.push('请选择计费模式');
            }

            // 验证重量规则
            if (!mappingStrategyForm.weightRules || mappingStrategyForm.weightRules.length === 0) {
                errors.push('至少需要一条重量规则');
            } else {
                // 验证每个重量规则
                mappingStrategyForm.weightRules.forEach((rule, index) => {
                    const ruleIndex = index + 1;

                    if (!rule.upperBound || rule.upperBound < 0) {
                        errors.push(`第${ruleIndex}条规则的重量上限不能为负数`);
                    }

                    if (rule.freight !== null && rule.freight !== undefined && rule.freight < 0) {
                        errors.push(`第${ruleIndex}条规则的邮资不能为负数`);
                    }





                    // V3版本：仅需验证重量上限和费用，首重续重信息从 strategy_area_pricing 表获取
                });

                // 验证重量上限的合理性（递增排序）
                for (let i = 1; i < mappingStrategyForm.weightRules.length; i++) {
                    const currentRule = mappingStrategyForm.weightRules[i];
                    const previousRule = mappingStrategyForm.weightRules[i - 1];

                    if (currentRule.upperBound <= previousRule.upperBound) {
                        errors.push(`第${i + 1}条规则的重量上限必须大于第${i}条规则`);
                    }
                }
            }

            return {
                isValid: errors.length === 0,
                errors: errors
            };
        };

        // 区域选择器相关方法
        const openAreaSelector = () => {
            buildAreaTree(); // 确保区域树已构建
            showMappingAreaSelector.value = true;
            console.log('🌍 打开区域选择器');
        };

        const closeMappingAreaSelector = () => {
            showMappingAreaSelector.value = false;
            console.log('❌ 关闭区域选择器');
        };

        const confirmAreaSelection = () => {
            // 将选中的区域保存到表单中
            const selectedAreas = [];

            // 添加选中的省份
            mappingAreaState.selectedProvinces.forEach(provinceId => {
                selectedAreas.push({ type: 'province', id: provinceId });
            });

            // 添加选中的城市
            mappingAreaState.selectedCities.forEach(cityId => {
                selectedAreas.push({ type: 'city', id: cityId });
            });

            // 添加选中的区县
            mappingAreaState.selectedDistricts.forEach(districtId => {
                selectedAreas.push({ type: 'district', id: districtId });
            });

            mappingStrategyForm.selectedAreas = selectedAreas;
            showMappingAreaSelector.value = false;

            console.log('✅ 确认区域选择，选中', selectedAreas.length, '个区域');
        };

        const getSelectedAreasCount = () => {
            return mappingStrategyForm.selectedAreas ? mappingStrategyForm.selectedAreas.length : 0;
        };

        const getMappingSelectedAreaTags = () => {
            const tags = [];

            if (!mappingStrategyForm.selectedAreas) return tags;

            mappingStrategyForm.selectedAreas.forEach(area => {
                let areaInfo = null;
                let text = '';

                if (area.type === 'province') {
                    areaInfo = (areaTree.value || []).find(p => p.id === area.id);
                    text = areaInfo ? areaInfo.name : '未知省份';
                } else if (area.type === 'city') {
                    for (const province of areaTree.value) {
                        const city = province.children?.find(c => c.id === area.id);
                        if (city) {
                            text = `${province.name}-${city.name}`;
                            break;
                        }
                    }
                } else if (area.type === 'district') {
                    for (const province of areaTree.value) {
                        for (const city of (province.children || [])) {
                            const district = city.children?.find(d => d.id === area.id);
                            if (district) {
                                text = `${province.name}-${city.name}-${district.name}`;
                                break;
                            }
                        }
                        if (text) break;
                    }
                }

                if (text) {
                    tags.push({
                        id: area.id,
                        text: text,
                        type: area.type
                    });
                }
            });

            return tags;
        };

        const removeMappingAreaTag = (tagId, tagType) => {
            if (!mappingStrategyForm.selectedAreas) return;

            mappingStrategyForm.selectedAreas = mappingStrategyForm.selectedAreas.filter(
                area => !(area.id === tagId && area.type === tagType)
            );

            // 同步更新选择器状态
            if (tagType === 'province') {
                mappingAreaState.selectedProvinces.delete(tagId);
            } else if (tagType === 'city') {
                mappingAreaState.selectedCities.delete(tagId);
            } else if (tagType === 'district') {
                mappingAreaState.selectedDistricts.delete(tagId);
            }

            console.log('🗑️ 移除区域标签:', tagType, tagId);
        };

        // 策略编辑的区域选择方法
        const toggleMappingProvinceSelection = (province) => {
            if (mappingAreaState.selectedProvinces.has(province.id)) {
                mappingAreaState.selectedProvinces.delete(province.id);
            } else {
                mappingAreaState.selectedProvinces.add(province.id);
            }
        };

        const toggleMappingProvinceExpansion = (province) => {
            if (mappingAreaState.expandedProvinces.has(province.id)) {
                mappingAreaState.expandedProvinces.delete(province.id);
            } else {
                mappingAreaState.expandedProvinces.add(province.id);
            }
        };

        const toggleMappingCitySelection = (city, province) => {
            if (mappingAreaState.selectedCities.has(city.id)) {
                mappingAreaState.selectedCities.delete(city.id);
            } else {
                mappingAreaState.selectedCities.add(city.id);
            }
        };

        const toggleMappingCityExpansion = (city) => {
            if (mappingAreaState.expandedCities.has(city.id)) {
                mappingAreaState.expandedCities.delete(city.id);
            } else {
                mappingAreaState.expandedCities.add(city.id);
            }
        };

        const toggleMappingDistrictSelection = (district, city, province) => {
            if (mappingAreaState.selectedDistricts.has(district.id)) {
                mappingAreaState.selectedDistricts.delete(district.id);
            } else {
                mappingAreaState.selectedDistricts.add(district.id);
            }
        };

        // 辅助方法定义
        const getAllAreas = () => {
            return areas.value || [];
        };

        // 映射详情加载方法
        const loadMappingDetails = async () => {
            console.log('🗺️ 映射详情加载开始，策略ID:', selectedMappingStrategyId.value);

            if (!selectedMappingStrategyId.value) {
                console.log('⚠️ 未选择策略，清空数据');
                mappingMergedData.value = [];
                mappingGroupByAreaData.value = [];
                filteredAssignments.value = [];
                return;
            }

            try {
                console.log('🔄 并行加载映射数据和分配数据...');

                // 并行加载合并映射数据、按区域分组数据和分配数据
                const [mergedMappingsResult, groupByAreaResult, assignmentsResult] = await Promise.all([
                    api.getMappingsMerged({ strategyId: selectedMappingStrategyId.value }),
                    api.getMappingsGroupByArea({ strategyId: selectedMappingStrategyId.value }),
                    api.getAssignments({ strategyId: selectedMappingStrategyId.value })
                ]);

                console.log('📊 数据加载结果:', {
                    mergedMappingsResult: mergedMappingsResult,
                    groupByAreaResult: groupByAreaResult,
                    assignmentsResult: assignmentsResult
                });

                // 处理合并映射数据，确保包含首重续重信息
                if (mergedMappingsResult.code === 0) {
                    const mappingData = mergedMappingsResult.data || [];
                    // 确保每个映射项都包含首重续重信息
                    mappingMergedData.value = mappingData.map(item => ({
                        ...item,
                        // 如果没有首重续重信息，设置默认值
                        firstWeightKg: item.firstWeightKg || '-',
                        firstWeightFee: item.firstWeightFee || '-',
                        additionalWeightKg: item.additionalWeightKg || '-',
                        additionalWeightFee: item.additionalWeightFee || '-',
                        volumetricWeightRatio: item.volumetricWeightRatio || '-'
                    }));
                    console.log('✅ 合并映射数据加载成功:', mappingMergedData.value.length, '条');
                } else {
                    mappingMergedData.value = [];
                    console.warn('❌ 合并映射数据加载失败:', mergedMappingsResult.msg);
                }

                // 处理按区域分组数据，确保包含首重续重信息
                if (groupByAreaResult.code === 0) {
                    const areaGroupData = groupByAreaResult.data || [];
                    mappingGroupByAreaData.value = areaGroupData.map(areaGroup => ({
                        ...areaGroup,
                        // 确保区域级别的首重续重信息
                        firstWeightKg: areaGroup.firstWeightKg || '-',
                        firstWeightFee: areaGroup.firstWeightFee || '-',
                        additionalWeightKg: areaGroup.additionalWeightKg || '-',
                        additionalWeightFee: areaGroup.additionalWeightFee || '-',
                        volumetricWeightRatio: areaGroup.volumetricWeightRatio || '-'
                    }));
                    console.log('✅ 按区域分组数据加载成功:', mappingGroupByAreaData.value.length, '个区域');
                } else {
                    mappingGroupByAreaData.value = [];
                    console.warn('❌ 按区域分组数据加载失败:', groupByAreaResult.msg);
                }

                // 处理策略分配数据
                if (assignmentsResult.code === 0) {
                    filteredAssignments.value = assignmentsResult.data || [];
                    console.log('✅ 策略分配加载成功:', filteredAssignments.value.length, '条');
                } else {
                    filteredAssignments.value = [];
                    console.warn('❌ 策略分配加载失败:', assignmentsResult.msg);
                }

                console.log('✅ 映射详情加载完成，结果状态:', {
                    mappingCount: mappingMergedData.value.length,
                    areaGroupCount: mappingGroupByAreaData.value.length,
                    assignmentCount: filteredAssignments.value.length,
                    selectedStrategyId: selectedMappingStrategyId.value
                });

            } catch (err) {
                console.error('❌ 加载映射详情异常:', err);
                mappingMergedData.value = [];
                mappingGroupByAreaData.value = [];
                filteredAssignments.value = [];
                showMessage('加载映射详情失败: ' + err.message, true);
            }
        };



        const getSelectedAreaTags = () => {
            const tags = [];

            // 省份标签
            cascaderState.selectedProvinces.forEach(provinceId => {
                const province = (areaTree.value || []).find(p => p.id === provinceId);
                if (province) {
                    tags.push({
                        id: provinceId,
                        text: province.name,
                        type: 'province'
                    });
                }
            });

            // 城市标签
            cascaderState.selectedCities.forEach(cityId => {
                for (const province of areaTree.value) {
                    const city = province.children?.find(c => c.id === cityId);
                    if (city) {
                        tags.push({
                            id: cityId,
                            text: `${province.name}-${city.name}`,
                            type: 'city'
                        });
                        break;
                    }
                }
            });

            // 区县标签
            cascaderState.selectedDistricts.forEach(districtId => {
                for (const province of areaTree.value) {
                    for (const city of (province.children || [])) {
                        const district = city.children?.find(d => d.id === districtId);
                        if (district) {
                            tags.push({
                                id: districtId,
                                text: `${province.name}-${city.name}-${district.name}`,
                                type: 'district'
                            });
                            return;
                        }
                    }
                }
            });

            return tags;
        };

        const removeSelectedAreaTag = (tagId, tagType) => {
            if (tagType === 'province') {
                cascaderState.selectedProvinces.delete(tagId);
            } else if (tagType === 'city') {
                cascaderState.selectedCities.delete(tagId);
            } else if (tagType === 'district') {
                cascaderState.selectedDistricts.delete(tagId);
            }
        };

        // 计算属性
        const strategiesComputed = computed(() => {
            // 确保返回过滤后的有效策略数据
            return (strategies.value || []).filter(strategy =>
                strategy && typeof strategy === 'object' && strategy.name
            );
        });

        // 监听selectedMappingStrategyId变化，更新filteredWeightRules
        // 切换显示模式
        const switchDisplayMode = (mode) => {
            displayMode.value = mode;
            console.log('切换显示模式为:', mode);

            // 如果切换到按区域显示模式，且数据为空，则重新加载
            if (mode === 'by-area' && mappingGroupByAreaData.value.length === 0 && selectedMappingStrategyId.value) {
                loadMappingDetails();
            }
        };

        // 编辑区域重量规则
        const editAreaWeightRule = (areaId, ruleId) => {
            console.log('编辑区域重量规则:', { areaId, ruleId });
            // TODO: 实现编辑逻辑
            showMessage('编辑功能待实现');
        };

        // 删除区域重量规则
        const deleteAreaWeightRule = async (mappingId) => {
            if (!confirm('确定要删除这个映射关系吗？')) return;

            try {
                const result = await api.deleteMapping({ id: mappingId });
                if (result.code === 0) {
                    showMessage('删除成功');
                    // 重新加载映射详情
                    if (selectedMappingStrategyId.value) {
                        loadMappingDetails();
                    }
                } else {
                    showMessage(result.msg || '删除失败', true);
                }
            } catch (err) {
                showMessage(err.message, true);
            }
        };

        const updateFilteredWeightRules = async () => {
            if (selectedMappingStrategyId.value) {
                try {
                    const result = await api.getWeightRules(selectedMappingStrategyId.value);
                    if (result.code === 0) {
                        filteredWeightRules.value = result.data || [];
                    } else {
                        filteredWeightRules.value = [];
                    }
                } catch (err) {
                    console.error('获取重量规则失败:', err);
                    filteredWeightRules.value = [];
                }
            } else {
                filteredWeightRules.value = [];
            }
        };

        // 监听selectedMappingStrategyId变化
        watch(selectedMappingStrategyId, updateFilteredWeightRules);

        // 组件挂载时加载数据
        onMounted(() => {
            console.log('🚀 应用初始化开始...');
            Promise.all([
                loadAreas(), // 使用普通接口，首页运费计算不需要分页
                loadStrategies(),
                loadMappings(),
                loadAssignments()
            ]).then(() => {
                console.log('✅ 应用初始化完成');
            }).catch(err => {
                console.error('❌ 应用初始化失败:', err);
            });
        });

        return {
            // 响应式数据
            activeTab, calculating, submitting, error, successMsg, freightResult, showFormulaDetails,
            freightForm, strategyForm, areaForm, mappingForm, batchMappingForm, editMappingForm,
            weightRuleForm, assignmentForm, batchAssignmentForm,
            areas, strategies, mappings, weightRules, assignments, batchWeightRules,
            filteredAssignments, mappingMergedData, mappingGroupByAreaData, displayMode, filteredWeightRules,
            showAddStrategyModal, showEditStrategyModal, showCopyStrategyModal, showAddAreaModal, showEditAreaModal,
            showAddMappingModal, showBatchMappingModal, showEditMappingModal, showAddWeightRuleModal,
            showEditWeightRuleModal, showAddAssignmentModal, showBatchAssignmentModal,
            currentStrategyForCopy,
            copyStrategyForm, copyStrategyNewName, copyStrategyDescription,
            // 策略编辑相关状态（用于映射管理页面）
            showMappingStrategyEditModal, submittingMappingStrategy, mappingStrategyForm,
            // 区域选择器状态
            showMappingAreaSelector, mappingAreaState,
            // V3策略配置相关状态
            showV3StrategyEditModal, showV3AreaSelector, submittingV3Strategy,
            v3StrategyEditForm, v3AreaState, v3SelectedAreaTags, updateV3AreaTags, showV3PricingRulesModal, submittingV3PricingRules, v3PricingRulesForm, v3CurrentStrategy, v3AreaSelectionCallback,
            selectedStrategyId, selectedMappingStrategyId,
            // 策略区域配置相关状态
            selectedAreaConfigStrategyId, selectedAreaConfigAreaId, selectedAreaDetail,
            strategyAreaDetails, isEditingAreaConfig, savingAreaConfig, currentWeightSegmentRules,
            showAddWeightSegmentModal, showEditWeightSegmentModal, areaConfigForm, weightSegmentForm,
            strategySearchKeyword, showStrategyDropdown, filteredStrategies,
            weightRulesSearchKeyword, showWeightRulesStrategyDropdown, filteredWeightRulesStrategies,
            showAreaSelector, selectedProvince, selectedCity, selectedDistrict, areaTree,
            cascaderState,

            // 核心方法
            calculateFreight, resetFreightForm,
            toggleFormulaDetails: () => {
                showFormulaDetails.value = !showFormulaDetails.value;
            },
            loadAreas, loadAreasWithPage, loadStrategies, loadMappings, loadAssignments, loadWeightRules,
            deleteWeightRule, editWeightRule, submitWeightRule, closeWeightRuleModal, addWeightRuleForStrategy,
            buildAreaTree, toggleAreaSelector, expandProvince, selectProvince, expandCity, selectCity, selectDistrict,
            clearAreaSelection, getSelectedAreaText, handleAreaSelectorMouseLeave, handleAreaSelectorMouseEnter,
            handleStrategySearch, showStrategyOptions, hideStrategyDropdown, handleStrategySelection,
            handleWeightRulesStrategySearch, showWeightRulesStrategyOptions, hideWeightRulesStrategyDropdown,
            handleWeightRulesStrategySelection, selectWeightRulesStrategy, clearWeightRulesSearch,
            switchTab, formatAreaName, formatDate, getStrategyName, getAreaName, findAreaNameById,
            addStrategy, addWeightRule, addMapping, addBatchMappings, addAssignment, addBatchAssignments,

            // 复制策略相关方法
            copyAndCreateStrategy, closeCopyStrategyModal, submitCopyStrategy,

            // 策略导入导出方法
            exportStrategy: async () => {
                try {
                    console.log('📊 开始导出策略数据...');
                    const result = await apiCalls.exportStrategies();
                    if (result) {
                        // 创建下载链接
                        const url = window.URL.createObjectURL(new Blob([result]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', `策略数据_${new Date().getTime()}.xlsx`);
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                        window.URL.revokeObjectURL(url);
                        console.log('✅ 策略数据导出成功');
                    }
                } catch (error) {
                    console.error('❌ 策略数据导出失败:', error);
                    showMessage('导出失败: ' + error.message, true);
                }
            },

            importStrategy: async (file) => {
                try {
                    console.log('📊 开始导入策略数据...');
                    const formData = new FormData();
                    formData.append('file', file);
                    const result = await apiCalls.importStrategies(formData);
                    if (result.code === 0) {
                        showMessage('导入成功: ' + (result.msg || '策略数据已成功导入'));
                        await loadStrategies(); // 重新加载策略列表
                        console.log('✅ 策略数据导入成功');
                    } else {
                        throw new Error(result.msg || '导入失败');
                    }
                } catch (error) {
                    console.error('❌ 策略数据导入失败:', error);
                    showMessage('导入失败: ' + error.message, true);
                }
            },
            // 策略编辑方法
            editStrategyInMapping,

            // 策略编辑相关方法（用于映射管理页面）
            editSelectedStrategy, submitMappingStrategyEdit, closeMappingStrategyEditModal,
            resetMappingStrategyForm, validateMappingStrategyForm, addMappingStrategyWeightRule, removeMappingStrategyWeightRule,
            // 区域选择器方法
            openAreaSelector, closeMappingAreaSelector, confirmAreaSelection, getSelectedAreasCount,
            getMappingSelectedAreaTags, removeMappingAreaTag,
            toggleMappingProvinceSelection, toggleMappingProvinceExpansion,
            toggleMappingCitySelection, toggleMappingCityExpansion, toggleMappingDistrictSelection,
            submitBatchMapping, submitBatchAssignment, submitMapping, submitEditMapping, submitAssignment,
            loadWeightRulesForMapping, loadWeightRulesForBatch,
            closeMappingModal, closeBatchMappingModal, closeEditMappingModal, closeAssignmentModal, closeBatchAssignmentModal,
            getBatchAssignmentPreviewCount,

            // 查询方法 - 修复问题一
            searchStrategies, resetStrategyQuery, editStrategy, deleteStrategy, toggleStrategyStatus,
            getStrategyStatusText, getStrategyStatusClass, closeStrategyModal, submitStrategy,
            searchAssignments, resetAssignmentQuery, selectAssignment, selectStrategyFromList, getDisplayAssignments,
            searchMappings, resetMappingQuery, deleteMappingRuleForAreas,
            searchAreas, searchAreasWithPage, resetAreaQuery, addArea, editArea, deleteArea, exportAreas,
            getAreaLevelName, closeAreaModal, onLevelChange, submitArea,
            areaPagination, goToPage, previousPage, nextPage, changePageSize, getPageNumbers,
            editMappingRuleForAreas,

            // 新增：三栏布局支持方法
            getAllWeightRules, formatWeightRange, getFirstWeightFee, getAdditionalWeight, getAdditionalFee,
            allWeightRules,

            // 策略分配相关方法 - 修复问题三
            toggleProvinceSelection, toggleCitySelection, toggleDistrictSelection,
            toggleProvinceExpansion, toggleCityExpansion, isProvinceIndeterminate, isCityIndeterminate,

            // 联动功能相关状态和方法
            isLinkageEnabled: computed({
                get: () => cascaderState.isLinkageEnabled,
                set: (value) => {
                    cascaderState.isLinkageEnabled = value;
                    console.log('🔗 联动状态变更:', value ? '已启用' : '已禁用');
                }
            }),
            toggleLinkage,

            // 全选功能方法
            toggleSelectAllProvinces,
            toggleSelectAllCities,
            toggleSelectAllDistricts,
            isAllProvincesSelected,
            isAllExpandedCitiesSelected,
            isAllExpandedDistrictsSelected,
            clearAllSelections,
            getSelectedAreaTags,
            removeSelectedAreaTag,
            getAssignmentStatusClass, getAssignmentStatusText, toggleAssignmentStatus,

            // 查询条件对象
            selectedAssignment, selectedAssignmentIds, forceUpdateFlag,

            // 计算属性和数据获取方法
            strategiesComputed, getAllAreas, loadMappingDetails,

            // 映射管理相关方法
            switchDisplayMode, editAreaWeightRule, deleteAreaWeightRule,

            // 策略区域配置方法
            handleAreaConfigStrategySelection, selectAreaForConfig, startEditingAreaConfig,
            cancelEditingAreaConfig, saveAreaConfig, showAddWeightSegmentRule,
            editWeightSegmentRule, removeWeightSegmentRule, closeWeightSegmentModal,
            submitWeightSegmentRule,





            // 查询表单数据导出
            strategyQuery,
            assignmentQuery,
            areaQuery,
            mappingQuery,
            selectedAssignment,
            selectedAssignmentIds,
            forceUpdateFlag,

            // 缺失的方法定义
            batchDeleteAssignments: async () => {
                if (selectedAssignmentIds.value.length === 0) {
                    showMessage('请选择要删除的记录', true);
                    return;
                }

                if (!confirm(`确定要删除选中的 ${selectedAssignmentIds.value.length} 条记录吗？`)) return;

                try {
                    const result = await api.batchDeleteAssignments(selectedAssignmentIds.value);
                    if (result.code === 0) {
                        showMessage(result.msg || '批量删除成功');
                        selectedAssignmentIds.value = [];
                        await loadAssignments();
                    } else {
                        showMessage(result.msg || '批量删除失败', true);
                    }
                } catch (err) {
                    showMessage(err.message, true);
                }
            },
            deleteAssignment: async (assignmentId) => {
                if (!assignmentId) {
                    showMessage('无效的分配ID', true);
                    return;
                }

                if (!confirm('确定要删除这个分配吗？')) return;

                try {
                    const result = await api.deleteAssignment(assignmentId);
                    if (result.code === 0) {
                        showMessage('删除成功');
                        await loadAssignments();
                    } else {
                        showMessage(result.msg || '删除失败', true);
                    }
                } catch (err) {
                    showMessage(err.message, true);
                }
            },

            toggleAllAssignments: (event) => {
                const checked = event.target.checked;
                if (checked) {
                    selectedAssignmentIds.value = (assignments.value || []).map(a => a.id);
                } else {
                    selectedAssignmentIds.value = [];
                }
            },

            allAssignmentsSelected: () => {
                return (assignments.value || []).length > 0 &&
                       selectedAssignmentIds.value.length === (assignments.value || []).length;
            },

            refreshData: () => {
                forceUpdateFlag.value++;
            },

            // V3策略配置相关方法
            closeV3StrategyEditModal: () => {
                showV3StrategyEditModal.value = false;
                // 重置表单
                Object.assign(v3StrategyEditForm, {
                    id: null,
                    name: '',
                    description: '',
                    pricingModel: '',
                    weightRules: [],
                    selectedAreas: []
                });
                // 重置区域选择器状态
                v3AreaState.selectedProvinces.clear();
                v3AreaState.selectedCities.clear();
                v3AreaState.selectedDistricts.clear();
                v3AreaState.expandedProvinces.clear();
                v3AreaState.expandedCities.clear();
            },

            submitV3StrategyEdit: async () => {
                console.log('提交V3策略编辑:', v3StrategyEditForm);
                // TODO: 实现提交逻辑
            },

            openV3AreaSelector: () => {
                console.log('🚀 打开V3地区选择器');

                // 💡 关键修复：每次打开都彻底清空地区选择器状态
                console.log('🧹 清空地区选择器状态...');
                v3AreaState.selectedProvinces.clear();
                v3AreaState.selectedCities.clear();
                v3AreaState.selectedDistricts.clear();
                v3AreaState.expandedProvinces.clear();
                v3AreaState.expandedCities.clear();

                // 清空其他相关状态
                if (window.vueAppInstance) {
                    if (window.vueAppInstance.v3AreaState) {
                        window.vueAppInstance.v3AreaState.selectedAreas = [];
                        window.vueAppInstance.v3AreaState.selectedAreaIds = [];
                    }
                    // 清除编辑模式标识（新增模式）
                    window.vueAppInstance.currentEditingPricingId = null;
                }

                // 🔧 强制重置DOM复选框状态（延迟确保视图已渲染）
                setTimeout(() => {
                    const checkboxes = document.querySelectorAll('#v3-area-selector input[type="checkbox"]');
                    console.log('🔧 重置', checkboxes.length, '个复选框状态');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = false;
                        checkbox.indeterminate = false; // 清除半选状态
                    });

                    // 重置全选/清空按钮状态
                    const selectAllBtns = document.querySelectorAll('#v3-area-selector .select-all-btn, #v3-area-selector .clear-all-btn');
                    selectAllBtns.forEach(btn => {
                        if (btn.textContent.includes('全选')) {
                            btn.style.display = 'inline-block';
                        } else if (btn.textContent.includes('清空')) {
                            btn.style.display = 'none';
                        }
                    });

                    console.log('✅ DOM复选框状态重置完成');
                }, 150);

                showV3AreaSelector.value = true;
                console.log('✅ V3地区选择器已打开');
            },

            closeV3AreaSelector: () => {
                showV3AreaSelector.value = false;
            },

            // 💬 新增：重置地区选择器状态的公共方法
            resetV3AreaSelector: () => {
                console.log('🧹 重置地区选择器状态');

                // 清空 Vue 响应式状态
                v3AreaState.selectedProvinces.clear();
                v3AreaState.selectedCities.clear();
                v3AreaState.selectedDistricts.clear();
                v3AreaState.expandedProvinces.clear();
                v3AreaState.expandedCities.clear();

                // 清空标签显示
                v3SelectedAreaTags.value = [];

                // 清空其他相关状态
                if (window.vueAppInstance) {
                    if (window.vueAppInstance.v3AreaState) {
                        window.vueAppInstance.v3AreaState.selectedAreas = [];
                        window.vueAppInstance.v3AreaState.selectedAreaIds = [];
                    }
                    // 清除编辑模式标识
                    window.vueAppInstance.currentEditingPricingId = null;
                }

                // 强制重置 DOM 复选框状态
                setTimeout(() => {
                    const checkboxes = document.querySelectorAll('#v3-area-selector input[type="checkbox"]');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = false;
                        checkbox.indeterminate = false;
                    });

                    // 重置全选/清空按钮状态
                    const selectAllBtns = document.querySelectorAll('#v3-area-selector .select-all-btn, #v3-area-selector .clear-all-btn');
                    selectAllBtns.forEach(btn => {
                        if (btn.textContent.includes('全选')) {
                            btn.style.display = 'inline-block';
                        } else if (btn.textContent.includes('清空')) {
                            btn.style.display = 'none';
                        }
                    });
                }, 100);

                console.log('✅ 地区选择器状态重置完成');
            },

            confirmV3AreaSelection: async () => {
                try {
                    if (!v3CurrentStrategy.value) {
                        showMessage('请先选择一个策略', true);
                        return;
                    }

                    // [问题修复] 收集选中的所有区域 ID，添加详细日志和状态验证
                    const selectedAreaIds = [];

                    console.log('🔍 [问题修复] 开始收集选中地区...');

                    // [问题修复] 验证地区状态是否合理
                    const currentState = {
                        provinces: v3AreaState.selectedProvinces.size,
                        cities: v3AreaState.selectedCities.size,
                        districts: v3AreaState.selectedDistricts.size
                    };
                    console.log('📊 [调试] 当前地区选中状态:', currentState);

                    // 检查是否是编辑模式
                    const currentEditMode = (window.vueAppInstance && window.vueAppInstance.currentEditingPricingId) ||
                                     (window.V3StrategyEditModal && window.V3StrategyEditModal.currentEditingPricingId);

                    if (currentEditMode) {
                        const editingId = window.vueAppInstance?.currentEditingPricingId ||
                                        window.V3StrategyEditModal?.currentEditingPricingId;
                        console.log('📝 [调试] 编辑模式，配置ID:', editingId);
                    }

                    console.log('  - 省级选中数量:', v3AreaState.selectedProvinces.size);
                    console.log('  - 市级选中数量:', v3AreaState.selectedCities.size);
                    console.log('  - 区县级选中数量:', v3AreaState.selectedDistricts.size);

                    v3AreaState.selectedProvinces.forEach(id => {
                        selectedAreaIds.push(id);
                        console.log('  🏯 省级:', id);
                    });
                    v3AreaState.selectedCities.forEach(id => {
                        selectedAreaIds.push(id);
                        console.log('  🏢 市级:', id);
                    });
                    v3AreaState.selectedDistricts.forEach(id => {
                        selectedAreaIds.push(id);
                        console.log('  🏠 区县级:', id);
                    });

                    if (selectedAreaIds.length === 0) {
                        showMessage('请选择至少一个区域', true);
                        return;
                    }

                    console.log('📍 选中的区域ID列表:', selectedAreaIds);

                    // **性能优化：批量获取区域名称**
                    console.log('🚀 批量获取区域名称...');
                    const areaNames = await window.vueAppInstance.getAreaNamesOptimized(selectedAreaIds);
                    console.log('✅ 批量获取完成，区域名称:', areaNames);

                    // 检查是否是编辑模式
                    const isEditMode = (window.vueAppInstance && window.vueAppInstance.currentEditingPricingId) ||
                                     (window.V3StrategyEditModal && window.V3StrategyEditModal.currentEditingPricingId);

                    // **新增：在非编辑模式下检查策略+地区的唯一性（纯前端校验）**
                    if (!isEditMode) {
                        console.log('🔍 正在检查策略+地区的唯一性（纯前端校验）...', {
                            strategyId: v3CurrentStrategy.value.id,
                            selectedAreaIds: selectedAreaIds
                        });

                        // 调用v3-strategy-config.js中的重复检查函数（异步）
                        let duplicateCheckResult;
                        if (window.V3StrategyConfigManager && window.V3StrategyConfigManager.checkAreaDuplicate) {
                            try {
                                console.log('📡 调用异步重复检查函数...');
                                duplicateCheckResult = await window.V3StrategyConfigManager.checkAreaDuplicate(
                                    v3CurrentStrategy.value.id,
                                    selectedAreaIds
                                );
                                console.log('📄 异步检查结果:', duplicateCheckResult);
                            } catch (asyncError) {
                                console.error('❌ 异步重复检查失败:', asyncError);
                                duplicateCheckResult = {
                                    hasDuplicate: false,
                                    error: true,
                                    message: '地区重复检查异常，请谨慎操作'
                                };
                            }
                        } else {
                            // 回退到原有的检查逻辑
                            try {
                                // 前端纯客户端校验：检查当前页面是否有重复的地区配置
                                const duplicateAreaIds = [];

                                // 检查已显示的地区配置中是否存在重复的地区ID
                                const allDisplayedAreaIds = new Set();

                                // 遍历当前页面显示的所有地区配置，收集已使用的地区ID
                                const existingAreaConfigs = document.querySelectorAll('#areaDisplayContainer .area-config-item');
                                existingAreaConfigs.forEach(configElement => {
                                    const areaElements = configElement.querySelectorAll('[data-area-id]');
                                    areaElements.forEach(areaElement => {
                                        const areaId = parseInt(areaElement.getAttribute('data-area-id'));
                                        if (areaId && !isNaN(areaId)) {
                                            allDisplayedAreaIds.add(areaId);
                                        }
                                    });
                                });

                                // 检查新选择的地区是否与已显示的地区重复
                                for (const areaId of selectedAreaIds) {
                                    if (allDisplayedAreaIds.has(areaId)) {
                                        duplicateAreaIds.push(areaId);
                                    }
                                }

                                if (duplicateAreaIds.length > 0) {
                                    // 发现重复的地区，显示错误信息
                                    const duplicateAreaNames = duplicateAreaIds.map(areaId => {
                                        // 尝试从区域树中获取地区名称
                                        const areaName = findAreaNameById(areaId) || `地区ID:${areaId}`;
                                        return `${areaName}(当前页面已有配置)`;
                                    }).join('\n');

                                    duplicateCheckResult = {
                                        hasDuplicate: true,
                                        message: `以下地区在当前页面已有配置，不能重复添加：\n${duplicateAreaNames}`
                                    };
                                } else {
                                    duplicateCheckResult = { hasDuplicate: false };
                                }

                            } catch (error) {
                                console.error('❌ 前端重复性检查异常:', error);
                                // 检查异常时继续执行，但给出警告
                                duplicateCheckResult = {
                                    hasDuplicate: false,
                                    error: true,
                                    message: '地区重复性检查异常，请谨慎操作'
                                };
                            }
                        }

                        // 处理重复检查结果
                        if (duplicateCheckResult.hasDuplicate) {
                            // 使用弹框显示重复地区错误信息
                            alert(duplicateCheckResult.message);
                            return;
                        } else if (duplicateCheckResult.error) {
                            // 使用弹框显示检查异常警告
                            alert(duplicateCheckResult.message);
                        } else {
                            console.log('✅ 前端校验通过，未发现重复地区');
                        }
                    }

                    if (isEditMode) {
                        // 编辑模式：标记地区映射变更，等待统一保存
                        const editingPricingId = window.vueAppInstance.currentEditingPricingId ||
                                                window.V3StrategyEditModal.currentEditingPricingId;

                        console.log('📝 编辑模式：标记地区映射变更，等待统一保存，配置ID:', editingPricingId, '选中区域:', selectedAreaIds.length);

                        // 将地区变更信息存储到全局状态，供保存所有配置时使用
                        if (!window.pendingAreaChanges) {
                            window.pendingAreaChanges = new Map();
                        }
                        window.pendingAreaChanges.set(editingPricingId, {
                            pricingId: editingPricingId,
                            selectedAreaIds: selectedAreaIds,
                            operator: 'admin'
                        });

                        showMessage('地区配置已更新，请点击"保存所有配置"按钮统一保存');
                        showV3AreaSelector.value = false;

                        // [修复] 添加详细的回调函数状态检查
                        console.log('🔍 [修复] 检查回调函数状态...');
                        console.log('  - v3AreaSelectionCallback 存在:', !!v3AreaSelectionCallback);
                        console.log('  - v3AreaSelectionCallback.value 存在:', !!v3AreaSelectionCallback?.value);
                        console.log('  - v3AreaSelectionCallback.value 类型:', typeof v3AreaSelectionCallback?.value);
                        console.log('  - window.vueAppInstance 存在:', !!window.vueAppInstance);
                        console.log('  - window.vueAppInstance.v3AreaSelectionCallback 存在:', !!window.vueAppInstance?.v3AreaSelectionCallback);
                        console.log('  - window.vueAppInstance.v3AreaSelectionCallback.value 存在:', !!window.vueAppInstance?.v3AreaSelectionCallback?.value);
                        console.log('  - window.vueAppInstance.v3AreaSelectionCallback.value 类型:', typeof window.vueAppInstance?.v3AreaSelectionCallback?.value);

                        // 调用回调函数更新界面显示（性能优化：避免重复API调用）
                        if (typeof v3AreaSelectionCallback.value === 'function') {
                            console.log('🔄 [修复] 调用地区选择回调函数（编辑模式），配置ID:', editingPricingId);
                            try {
                                // [关键修复] 确保传递正确的编辑ID给更新方法
                                console.log('🔄 [修复] 编辑模式：只更新前端缓存，不重新加载API数据');
                                await window.vueAppInstance.updateV3AreaDisplayCache(editingPricingId, selectedAreaIds, areaNames);
                                console.log('✅ [修复] 地区显示更新完成');
                            } catch (error) {
                                console.error('❌ [修复] 缓存更新失败:', error);
                                // 回退到原始方案
                                console.log('🔄 [修复] 回退方案：调用原始回调函数');
                                await v3AreaSelectionCallback.value();
                            }
                        } else {
                            console.warn('⚠️ [修复] v3AreaSelectionCallback.value 不是函数，尝试替代方案...');

                            // [修复] 替代方案：直接调用更新方法
                            if (window.vueAppInstance && window.vueAppInstance.updateV3AreaDisplayCache) {
                                console.log('🔄 [修复] 使用替代方案：直接调用更新方法');
                                try {
                                    await window.vueAppInstance.updateV3AreaDisplayCache(editingPricingId, selectedAreaIds, areaNames);
                                    console.log('✅ [修复] 替代方案执行成功');
                                } catch (error) {
                                    console.error('❌ [修复] 替代方案也失败:', error);
                                }
                            } else {
                                console.error('❌ [修复] 没有可用的更新方法');
                            }
                        }

                        // [修复] 在更新完成后才清除编辑模式标记
                        if (window.vueAppInstance) {
                            window.vueAppInstance.currentEditingPricingId = null;
                        }
                        if (window.V3StrategyEditModal) {
                            window.V3StrategyEditModal.currentEditingPricingId = null;
                        }
                        console.log('📝 [修复] 已清除编辑模式标记');

                    } else {
                        // 新增模式：标记为待添加的地区配置，等待统一保存
                        console.log('🆕 新增模式：标记地区选择，等待统一保存:', {
                            strategyId: v3CurrentStrategy.value.id,
                            selectedAreaIds: selectedAreaIds
                        });

                        // 生成临时ID
                        const tempPricingId = 'temp_' + Date.now();

                        // 将新增信息存储到全局状态
                        if (!window.pendingNewAreaConfigs) {
                            window.pendingNewAreaConfigs = new Map();
                        }

                        // 生成配置名称下标 - 修复：需要同时考虑已保存的配置和暂存的配置
                        let configIndex = 1;

                        // 强制清理旧数据，避免缓存问题
                        console.log('🧹 [强制清理] 检查是否有需要清理的旧暂存数据...');
                        if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.size > 0) {
                            console.log('🧹 [强制清理] 发现', window.pendingNewAreaConfigs.size, '个旧暂存配置，将在计算下标时考虑');
                        }

                        // 1. 先从已保存的配置中获取最大下标（包括当前DOM中所有可见的配置）
                        const existingRows = document.querySelectorAll('#area-pricing-list tr[data-pricing-id]');
                        const existingIndices = [];

                        console.log('🔍 [修复] 当前DOM中的配置行数:', existingRows.length);

                        existingRows.forEach((row, index) => {
                            const nameInput = row.querySelector('input[data-field="name"]');
                            if (nameInput && nameInput.value) {
                                console.log(`🔍 [修复] 第${index + 1}行配置名称:`, nameInput.value);
                                const match = nameInput.value.match(/配置名称-(\d+)$/);
                                if (match) {
                                    const indexNum = parseInt(match[1]);
                                    existingIndices.push(indexNum);
                                    console.log('🔍 [修复] 从已保存配置提取下标:', nameInput.value, '->', indexNum);
                                } else {
                                    console.log('🔍 [修复] 配置名称格式不匹配:', nameInput.value);
                                }
                            }
                        });

                        // 2. 再从暂存配置中获取最大下标
                        if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.size > 0) {
                            console.log('🔍 [修复] 检查暂存配置名称下标生成...');
                            const configsArray = Array.from(window.pendingNewAreaConfigs.values());
                            console.log('🔍 [修复] 暂存配置数量:', configsArray.length);

                            configsArray.forEach(config => {
                                const configName = config.name || '';
                                console.log('🔍 [修复] 检查暂存配置名称:', configName);
                                const match = configName.match(/配置名称-(\d+)$/);
                                if (match) {
                                    const index = parseInt(match[1]);
                                    existingIndices.push(index);
                                    console.log('🔍 [修复] 从暂存配置提取下标:', configName, '->', index);
                                }
                            });
                        }

                        // 3. 计算新的下标
                        if (existingIndices.length > 0) {
                            const validIndices = existingIndices.filter(index => index > 0);
                            if (validIndices.length > 0) {
                                configIndex = Math.max(...validIndices) + 1;
                                console.log('🔍 [修复] 最大下标:', Math.max(...validIndices));
                            }
                        }

                        console.log('🔍 [修复] 所有提取的下标:', existingIndices);
                        console.log('🔍 [修复] 计算出的新下标:', configIndex);

                        // 确保配置名称下标正确
                        const finalConfigName = `配置名称-${configIndex}`;
                        console.log('🏷️ [修复] 最终配置名称:', finalConfigName);

                        window.pendingNewAreaConfigs.set(tempPricingId, {
                            strategyId: v3CurrentStrategy.value.id,
                            name: finalConfigName,
                            description: '默认定价配置',
                            firstWeightKg: 0,
                            firstWeightFee: 0,
                            additionalWeightKg: 0,
                            additionalWeightFee: 0,
                            volumetricWeightRatio: 0,
                            status: 1,
                            selectedAreaIds: selectedAreaIds,
                            operator: 'admin'
                        });

                        showMessage('地区配置已暂存，请点击"保存所有配置"按钮统一保存');
                        showV3AreaSelector.value = false;

                        // 更新区域标签显示
                        updateV3AreaTags();

                        // 调用回调函数更新界面显示
                        console.log('🔍 检查回调函数状态...');
                        console.log('  - window.vueAppInstance 存在:', !!window.vueAppInstance);
                        console.log('  - v3AreaSelectionCallback 存在:', !!window.vueAppInstance?.v3AreaSelectionCallback);
                        console.log('  - v3AreaSelectionCallback.value 存在:', !!window.vueAppInstance?.v3AreaSelectionCallback?.value);
                        console.log('  - v3AreaSelectionCallback.value 类型:', typeof window.vueAppInstance?.v3AreaSelectionCallback?.value);

                        // 性能优化：新增模式使用前端缓存更新，避免API调用
                        console.log('🚀 性能优化：使用前端缓存更新地区显示');
                        try {
                            // 直接更新前端缓存并刷新界面显示
                            await window.vueAppInstance.updateV3NewAreaConfigDisplay(tempPricingId, selectedAreaIds, areaNames);
                            console.log('✅ 前端缓存更新完成');
                        } catch (error) {
                            console.error('❌ 前端缓存更新失败:', error);
                            // 回退方案：调用原始回调函数
                            if (window.vueAppInstance &&
                                window.vueAppInstance.v3AreaSelectionCallback &&
                                typeof window.vueAppInstance.v3AreaSelectionCallback.value === 'function') {
                                console.log('🔄 回退方案：调用地区选择回调函数...');
                                try {
                                    await window.vueAppInstance.v3AreaSelectionCallback.value();
                                    console.log('✅ 地区选择回调函数执行完成');
                                } catch (callbackError) {
                                    console.error('❌ 回调函数执行失败:', callbackError);
                                }
                            }
                        }

                        // 在新增模式下，不调用selectStrategy避免覆盖回调函数的界面更新
                        // selectStrategy会重新从服务器加载数据，覆盖暂存的配置显示
                        console.log('📝 新增模式：跳过selectStrategy调用，保持暂存配置显示');
                    }
                } catch (error) {
                    console.error('🚫 保存区域选择失败:', error);
                    showMessage('保存失败: ' + error.message, true);
                }
            },

            getV3SelectedAreasCount: () => {
                return v3AreaState.selectedProvinces.size +
                       v3AreaState.selectedCities.size +
                       v3AreaState.selectedDistricts.size;
            },

            getV3SelectedAreaTags: async () => {
                const tags = [];
                const selectedIds = [];

                // 收集所有选中的区域ID
                v3AreaState.selectedProvinces.forEach(id => selectedIds.push({id, type: 'province'}));
                v3AreaState.selectedCities.forEach(id => selectedIds.push({id, type: 'city'}));
                v3AreaState.selectedDistricts.forEach(id => selectedIds.push({id, type: 'district'}));

                if (selectedIds.length === 0) {
                    return [];
                }

                try {
                    // 批量获取区域名称
                    const areaIds = selectedIds.map(item => item.id);
                    const areaNames = await window.vueAppInstance.getAreaNamesOptimized(areaIds);

                    // 构建标签数组
                    for (let i = 0; i < selectedIds.length; i++) {
                        const {id, type} = selectedIds[i];
                        const name = areaNames[i] || `地区ID:${id}`;

                        tags.push({
                            id: id,
                            text: name,
                            type: type
                        });
                    }

                    return tags;
                } catch (error) {
                    console.error('获取V3区域标签失败:', error);
                    // 回退到简单映射
                    return selectedIds.map(({id, type}) => ({
                        id: id,
                        text: `地区ID:${id}`,
                        type: type
                    }));
                }
            },

            removeV3AreaTag: (areaId, type) => {
                console.log('🗑️ 移除V3区域标签:', areaId, type);

                // 根据类型移除对应的区域选择
                if (type === 'province') {
                    v3AreaState.selectedProvinces.delete(areaId);
                    // 移除省份时，同时移除其下的所有城市和区县
                    const province = areaTree.value.find(p => p.id === areaId);
                    if (province && province.children) {
                        province.children.forEach(city => {
                            v3AreaState.selectedCities.delete(city.id);
                            if (city.children) {
                                city.children.forEach(district => {
                                    v3AreaState.selectedDistricts.delete(district.id);
                                });
                            }
                        });
                    }
                } else if (type === 'city') {
                    v3AreaState.selectedCities.delete(areaId);
                    // 移除城市时，同时移除其下的所有区县
                    const city = areaTree.value
                        .flatMap(province => province.children || [])
                        .find(c => c.id === areaId);
                    if (city && city.children) {
                        city.children.forEach(district => {
                            v3AreaState.selectedDistricts.delete(district.id);
                        });
                    }
                } else if (type === 'district') {
                    v3AreaState.selectedDistricts.delete(areaId);
                }

                // 更新标签显示
                updateV3AreaTags();
            },

            addV3StrategyWeightRule: () => {
                v3StrategyEditForm.weightRules.push({
                    id: null,
                    upperBound: null,
                    freight: null,
                    firstWeightKg: 1,
                    firstWeightFee: null,
                    additionalWeightKg: 1,
                    additionalWeightFee: null
                });
            },

            removeV3StrategyWeightRule: (index) => {
                if (v3StrategyEditForm.weightRules.length > 1) {
                    v3StrategyEditForm.weightRules.splice(index, 1);
                }
            },

            // V3计费规则编辑相关方法
            openV3PricingRulesModal: () => {
                if (!v3CurrentStrategy.value) {
                    showMessage('请先选择一个策略', true);
                    return;
                }

                // 生成配置名称下标
                let configIndex = 1;
                if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.size > 0) {
                    // 获取当前最大的下标并加1
                    console.log('🔍 [调试] 检查现有配置名称下标生成...');
                    const configsArray = Array.from(window.pendingNewAreaConfigs.values());
                    console.log('🔍 [调试] 现有配置数量:', configsArray.length);

                    const indices = configsArray
                        .map(config => {
                            const configName = config.name || '';
                            console.log('🔍 [调试] 检查配置名称:', configName);
                            const match = configName.match(/配置名称-(\d+)$/);
                            const result = match ? parseInt(match[1]) : 0;
                            console.log('🔍 [调试] 提取下标:', result);
                            return result;
                        })
                        .filter(index => index > 0); // 只保留有效的下标

                    console.log('🔍 [调试] 有效下标数组:', indices);

                    if (indices.length > 0) {
                        configIndex = Math.max(...indices) + 1;
                    }

                    console.log('🔍 [调试] 计算出的新下标:', configIndex);
                }

                // 初始化表单数据
                Object.assign(v3PricingRulesForm, {
                    strategyId: v3CurrentStrategy.value.id,
                    pricingId: null, // 新建配置
                    name: `配置名称-${configIndex}`,
                    description: '默认定价配置',
                    firstWeightKg: 1.0,
                    firstWeightFee: 0,
                    additionalWeightKg: 1.0,
                    additionalWeightFee: 0,
                    volumetricWeightRatio: 0,
                    status: 1,
                    weightRules: []
                });

                showV3PricingRulesModal.value = true;
            },

            closeV3PricingRulesModal: () => {
                showV3PricingRulesModal.value = false;
                // 重置表单
                Object.assign(v3PricingRulesForm, {
                    strategyId: null,
                    pricingId: null,
                    name: '',
                    description: '',
                    firstWeightKg: 1.0,
                    firstWeightFee: 0,
                    additionalWeightKg: 1.0,
                    additionalWeightFee: 0,
                    volumetricWeightRatio: 0,
                    status: 1,
                    weightRules: []
                });
                submittingV3PricingRules.value = false;
            },

            addV3PricingWeightRule: () => {
                v3PricingRulesForm.weightRules.push({
                    id: null,
                    upperBound: null,
                    freight: null,
                    firstWeightKg: null,
                    firstWeightFee: null,
                    additionalWeightKg: null,
                    additionalWeightFee: null
                });
            },

            removeV3PricingWeightRule: (index) => {
                if (confirm('确定要删除这个重量规则吗？')) {
                    v3PricingRulesForm.weightRules.splice(index, 1);
                }
            },

            saveV3PricingRules: async () => {
                try {
                    submittingV3PricingRules.value = true;

                    // 表单验证
                    if (!v3PricingRulesForm.name || !v3PricingRulesForm.name.trim()) {
                        showMessage('请输入配置名称', true);
                        return;
                    }

                    if (!v3PricingRulesForm.firstWeightKg || v3PricingRulesForm.firstWeightKg < 0) {
                        showMessage('请输入正确的首重重量', true);
                        return;
                    }

                    if (!v3PricingRulesForm.firstWeightFee || v3PricingRulesForm.firstWeightFee < 0) {
                        showMessage('请输入正确的首重费用', true);
                        return;
                    }

                    console.log('💾 保存V3计费规则:', v3PricingRulesForm);

                    // 先检查是否已有区域配置
                    const strategyPricingResult = await api.post('/strategy-area-pricing/list', {
                        strategyId: v3PricingRulesForm.strategyId
                    });

                    let shouldCreateNew = false;
                    let selectedAreaIds = [];

                    if (strategyPricingResult.code === 0 && strategyPricingResult.data && strategyPricingResult.data.length > 0) {
                        // 已有配置，使用现有的区域配置
                        log.info('使用现有定价配置');
                        shouldCreateNew = false;
                        // TODO: 从现有配置中获取区域ID，暂时使用默认值
                        selectedAreaIds = [1]; // 默认区域
                    } else {
                        // 没有配置，需要创建新的
                        // 获取当前选中的区域ID列表
                        v3AreaState.selectedProvinces.forEach(id => selectedAreaIds.push(id));
                        v3AreaState.selectedCities.forEach(id => selectedAreaIds.push(id));
                        v3AreaState.selectedDistricts.forEach(id => selectedAreaIds.push(id));

                        if (selectedAreaIds.length === 0) {
                            showMessage('请先选择区域，再设置计费规则', true);
                            return;
                        }
                        shouldCreateNew = true;
                    }

                    // 调用API保存定价配置
                    const pricingData = {
                        strategyId: v3PricingRulesForm.strategyId,
                        name: v3PricingRulesForm.name,
                        description: v3PricingRulesForm.description,
                        firstWeightKg: v3PricingRulesForm.firstWeightKg,
                        firstWeightFee: v3PricingRulesForm.firstWeightFee,
                        additionalWeightKg: v3PricingRulesForm.additionalWeightKg,
                        additionalWeightFee: v3PricingRulesForm.additionalWeightFee,
                        volumetricWeightRatio: v3PricingRulesForm.volumetricWeightRatio,
                        status: v3PricingRulesForm.status,
                        selectedAreaIds: selectedAreaIds,
                        operator: 'frontend_user'
                    };

                    // 保存定价配置
                    const result = await api.post('/strategy-area-pricing/add', pricingData);

                    if (result.code === 0) {
                        const pricingId = result.data && result.data.id ? result.data.id : result.data;

                        // 如果有重量规则，则保存重量规则
                        if (v3PricingRulesForm.weightRules.length > 0) {
                            for (const rule of v3PricingRulesForm.weightRules) {
                                if (rule.upperBound && rule.freight !== null && rule.freight !== undefined) {
                                    const weightRuleData = {
                                        strategyId: v3PricingRulesForm.strategyId,
                                        upperBound: rule.upperBound,
                                        freight: rule.freight,
                                        firstWeightKg: rule.firstWeightKg,
                                        firstWeightFee: rule.firstWeightFee,
                                        additionalWeightKg: rule.additionalWeightKg,
                                        additionalWeightFee: rule.additionalWeightFee,
                                        operator: 'frontend_user'
                                    };

                                    await api.post('/weight-segment-rule/add', weightRuleData);
                                }
                            }
                        }

                        showMessage('计费规则保存成功');
                        // 关闭模态框
                        showV3PricingRulesModal.value = false;

                        // 刷新V3策略配置页面数据
                        if (window.V3StrategyConfigManager && window.V3StrategyConfigManager.selectStrategy) {
                            await window.V3StrategyConfigManager.selectStrategy(v3PricingRulesForm.strategyId);
                        }
                    } else {
                        showMessage(result.msg || '保存失败', true);
                    }
                } catch (error) {
                    console.error('🚫 保存计费规则失败:', error);
                    showMessage('保存失败: ' + error.message, true);
                } finally {
                    submittingV3PricingRules.value = false;
                }
            },

            // 优化区域名称获取函数，使用缓存管理器
            getAreaNameOptimized: async (areaId) => {
                try {
                    if (window.areaCacheManager) {
                        // 确保缓存管理器已初始化
                        if (typeof window.areaCacheManager.initialize === 'function') {
                            await window.areaCacheManager.initialize();
                        }
                        return await window.areaCacheManager.getAreaName(areaId);
                    }
                    // 回退到原始方法
                    return findAreaNameById(areaId) || `地区ID:${areaId}`;
                } catch (error) {
                    console.error('获取区域名称失败:', error);
                    return `地区ID:${areaId}`;
                }
            },

            // 批量获取区域名称（高性能版本）
            getAreaNamesOptimized: async (areaIds) => {
                try {
                    if (window.areaCacheManager && Array.isArray(areaIds)) {
                        // 确保缓存管理器已初始化
                        if (typeof window.areaCacheManager.initialize === 'function') {
                            await window.areaCacheManager.initialize();
                        }
                        return await window.areaCacheManager.getAreaNames(areaIds);
                    }
                    // 回退到逐个查询
                    const names = [];
                    for (const areaId of areaIds) {
                        const name = findAreaNameById(areaId) || `地区ID:${areaId}`;
                        names.push(name);
                    }
                    return names;
                } catch (error) {
                    console.error('批量获取区域名称失败:', error);
                    return areaIds.map(id => `地区ID:${id}`);
                }
            },

            // 新增：前端缓存更新方法（编辑模式）
            updateV3AreaDisplayCache: async (pricingId, selectedAreaIds, areaNames) => {
                console.log('🔄 [app.js修复] 更新V3地区显示缓存（编辑模式）:', {
                    pricingId,
                    selectedAreaIds: selectedAreaIds.length,
                    areaNames: areaNames.length
                });

                try {
                    // 直接更新DOM中的地区显示，避免API调用
                    const targetRow = document.querySelector(`tr[data-pricing-id="${pricingId}"]`);
                    if (!targetRow) {
                        console.error('❌ [app.js修复] 未找到目标行元素:', pricingId);
                        return;
                    }

                    console.log('✅ [app.js修复] 找到目标行元素');

                    // [修复] 使用正确的DOM选择器路径
                    let areaCell = targetRow.querySelector('.area-info .area-tags');

                    if (!areaCell) {
                        console.log('⚠️ [app.js修复] 未找到 .area-info .area-tags，尝试其他选择器...');

                        // 尝试其他可能的选择器
                        const alternativeSelectors = [
                            '.area-tags',
                            'td:nth-child(2) .area-tags',
                            'td:nth-child(2) .area-info .area-tags',
                            '.area-info',
                            'td:nth-child(2) .area-info',
                            'td:nth-child(2)'
                        ];

                        for (const selector of alternativeSelectors) {
                            areaCell = targetRow.querySelector(selector);
                            if (areaCell) {
                                console.log('✅ [app.js修复] 使用备选选择器找到容器:', selector);
                                break;
                            }
                        }
                    }

                    if (!areaCell) {
                        console.error('❌ [app.js修复] 完全无法找到地区显示容器');
                        console.log('🔍 [app.js修复] 目标行HTML结构:', targetRow.innerHTML.substring(0, 500));
                        return;
                    }

                    // 生成新的地区标签HTML
                    const newAreaTagsHTML = areaNames.map((name, index) =>
                        `<span class="area-tag" data-area-id="${selectedAreaIds[index]}">${name}</span>`
                    ).join('');

                    console.log('🔄 [app.js修复] 新的地区标签HTML:', newAreaTagsHTML);

                    // [修复] 智能更新内容
                    if (areaCell.classList.contains('area-tags')) {
                        // 如果是 .area-tags 容器，直接替换内容
                        console.log('🔄 [app.js修复] 更新前 .area-tags 内容:', areaCell.innerHTML);
                        areaCell.innerHTML = newAreaTagsHTML;
                        console.log('🔄 [app.js修复] 更新后 .area-tags 内容:', areaCell.innerHTML);
                    } else if (areaCell.classList.contains('area-info')) {
                        // 如果是 .area-info 容器，查找或创建 .area-tags
                        let innerAreaTags = areaCell.querySelector('.area-tags');
                        if (innerAreaTags) {
                            console.log('🔄 [app.js修复] 更新 .area-info 内的 .area-tags');
                            innerAreaTags.innerHTML = newAreaTagsHTML;
                        } else {
                            console.log('🔄 [app.js修复] 在 .area-info 中创建新的 .area-tags');
                            areaCell.innerHTML = `<div class="area-tags">${newAreaTagsHTML}</div>`;
                        }
                    } else {
                        // 其他情况，创建完整的地区信息结构
                        console.log('🔄 [app.js修复] 创建完整的地区信息结构');
                        areaCell.innerHTML = `<div class="area-info"><div class="area-tags">${newAreaTagsHTML}</div></div>`;
                    }

                    console.log('✅ [app.js修复] 编辑模式地区显示更新完成');

                    // 添加视觉反馈
                    areaCell.style.backgroundColor = '#e8f5e8';
                    areaCell.style.transition = 'background-color 0.3s ease';
                    setTimeout(() => {
                        areaCell.style.backgroundColor = '';
                    }, 1500);

                    // 同时更新全局状态中的地区信息
                    if (window.pendingAreaChanges && window.pendingAreaChanges.has(pricingId)) {
                        window.pendingAreaChanges.get(pricingId).selectedAreaIds = selectedAreaIds;
                    }

                } catch (error) {
                    console.error('❌ [app.js修复] 更新地区显示缓存失败:', error);
                    throw error;
                }
            },

            // 新增：前端缓存更新方法（新增模式）
            updateV3NewAreaConfigDisplay: async (tempPricingId, selectedAreaIds, areaNames) => {
                console.log('🔄 更新V3新增地区配置显示:', {
                    tempPricingId,
                    selectedAreaIds: selectedAreaIds.length,
                    areaNames: areaNames.length
                });

                try {
                    // 更新暂存数据中的地区信息
                    if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.has(tempPricingId)) {
                        const config = window.pendingNewAreaConfigs.get(tempPricingId);
                        config.selectedAreaIds = selectedAreaIds;
                        config.areaNames = areaNames; // 添加缓存的地区名称

                        console.log('✅ 暂存配置地区信息更新完成');
                    }

                    // 立即刷新界面显示（使用缓存数据）
                    if (window.V3StrategyEditModal && typeof window.V3StrategyEditModal.currentStrategy === 'object') {
                        await window.vueAppInstance.refreshV3AreaDisplayWithCache();
                    }

                } catch (error) {
                    console.error('❌ 更新新增地区配置显示失败:', error);
                    throw error;
                }
            },

            // 新增：使用缓存数据刷新显示
            refreshV3AreaDisplayWithCache: async () => {
                console.log('🚀 使用缓存数据刷新V3地区显示（避免API调用）');

                try {
                    // 只更新前端显示，不调用API
                    const areaPricingList = document.getElementById('area-pricing-list');
                    if (areaPricingList) {
                        // [修复] 检查并清除空状态显示
                        const emptyStateRow = areaPricingList.querySelector('.empty-cell');
                        if (emptyStateRow) {
                            console.log('🧹 检测到空状态显示，准备清除');
                            emptyStateRow.parentElement.remove(); // 删除包含空状态的整行
                            console.log('✅ 空状态显示已清除');
                        }

                        // 保持现有数据，但添加暂存的新配置显示
                        if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.size > 0) {
                            // 清理旧的暂存显示
                            const oldPendingRows = areaPricingList.querySelectorAll('.pending-new-config');
                            oldPendingRows.forEach(row => row.remove());

                            // 添加新的暂存配置
                            window.pendingNewAreaConfigs.forEach((config, tempId) => {
                                const newRow = document.createElement('tr');
                                newRow.className = 'pending-new-config new-area-config';
                                newRow.setAttribute('data-temp-id', tempId);

                                const areaNames = config.areaNames || config.selectedAreaIds.map(id =>
                                    findAreaNameById(id) || `地区ID:${id}`);

                                newRow.innerHTML = `
                                    <td>
                                        <input type="text" value="${config.name}" 
                                               class="table-input name-input" 
                                               data-field="name" data-temp-id="${tempId}" 
                                               placeholder="请输入配置名称" 
                                               onchange="handlePendingConfigNameChange(this)">
                                    </td>
                                    <td class="area-names">
                                        ${areaNames.map((name, index) => 
                                            `<span class="area-tag" data-area-id="${config.selectedAreaIds[index]}">${name}</span>`
                                        ).join('')}
                                    </td>
                                    <td><input type="number" value="${config.firstWeightKg}" step="0.1" class="table-input" data-field="firstWeightKg" data-temp-id="${tempId}" onchange="handlePendingConfigFieldChange(this)" onblur="handlePendingConfigFieldBlur(this)"></td>
                                    <td><input type="number" value="${config.firstWeightFee}" step="0.1" class="table-input" data-field="firstWeightFee" data-temp-id="${tempId}" onchange="handlePendingConfigFieldChange(this)" onblur="handlePendingConfigFieldBlur(this)"></td>
                                    <td><input type="number" value="${config.additionalWeightKg}" step="0.1" class="table-input" data-field="additionalWeightKg" data-temp-id="${tempId}" onchange="handlePendingConfigFieldChange(this)" onblur="handlePendingConfigFieldBlur(this)"></td>
                                    <td><input type="number" value="${config.additionalWeightFee}" step="0.1" class="table-input" data-field="additionalWeightFee" data-temp-id="${tempId}" onchange="handlePendingConfigFieldChange(this)" onblur="handlePendingConfigFieldBlur(this)"></td>
                                    <td><input type="number" value="${config.volumetricWeightRatio}" step="0.1" class="table-input" data-field="volumetricWeightRatio" data-temp-id="${tempId}" onchange="handlePendingConfigFieldChange(this)" onblur="handlePendingConfigFieldBlur(this)"></td>
                                    <td>
                                        <input type="text" value="${config.description}" 
                                               class="table-input description-input" 
                                               data-field="description" data-temp-id="${tempId}" 
                                               placeholder="请输入描述" 
                                               onchange="handlePendingConfigFieldChange(this)">
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn-small btn-success" 
                                                    onclick="saveNewAreaConfig('${tempId}')" 
                                                    title="保存配置">
                                                <i class="icon-save"></i> 保存
                                            </button>
                                            <button class="btn-small btn-danger" 
                                                    onclick="cancelPendingAreaConfig('${tempId}')" 
                                                    title="取消暂存配置">
                                                <i class="icon-cancel"></i> 取消
                                            </button>
                                        </div>
                                    </td>
                                `;

                                areaPricingList.appendChild(newRow);
                                console.log('✅ 新增配置行已添加:', config.name);
                            });

                            console.log('✅ 暂存配置显示刷新完成');
                        }
                    }

                } catch (error) {
                    console.error('❌ 使用缓存数据刷新显示失败:', error);
                    throw error;
                }
            },

            // 新增：获取地区信息（支持级别和父级信息）
            getAreaInfoById: async (areaId) => {
                try {
                    // 先从地区树中查找
                    if (areaTree.value && areaTree.value.length > 0) {
                        const findAreaInfo = (nodes, level = 1, parentId = null, cityParentId = null) => {
                            for (const node of nodes) {
                                if (node.id === areaId || node.areaId === areaId) {
                                    return {
                                        id: node.id || node.areaId,
                                        name: node.name || node.areaName,
                                        level: level,
                                        parentId: parentId,
                                        cityParentId: cityParentId
                                    };
                                }

                                if (node.children && node.children.length > 0) {
                                    const found = findAreaInfo(node.children, level + 1,
                                        node.id || node.areaId,
                                        level === 1 ? (node.id || node.areaId) : cityParentId);
                                    if (found) return found;
                                }
                            }
                            return null;
                        };

                        const areaInfo = findAreaInfo(areaTree.value);
                        if (areaInfo) {
                            console.log('✅ 从地区树找到地区信息:', areaInfo);
                            return areaInfo;
                        }
                    }

                    // 地区树中没有找到，使用API查询
                    console.log('📋 地区树中未找到，使用API查询地区信息:', areaId);

                    // 使用统一API服务查询
                    const result = await api.getAreaById(areaId);
                    if (result.code === 0 && result.data) {
                        const area = result.data;
                        const areaInfo = {
                            id: area.areaId || area.id,
                            name: area.name || area.areaName,
                            level: area.level,
                            parentId: area.parentId,
                            cityParentId: area.cityParentId
                        };

                        console.log('✅ 从API获取地区信息:', areaInfo);
                        return areaInfo;
                    }

                    console.warn('⚠️ 未找到地区信息:', areaId);
                    return null;

                } catch (error) {
                    console.error('❌ 获取地区信息失败:', error);
                    return null;
                }
            },

            toggleV3ProvinceSelection: (province) => {
                if (v3AreaState.selectedProvinces.has(province.id)) {
                    v3AreaState.selectedProvinces.delete(province.id);
                    // 取消选择省份时，同时取消下级所有选择
                    if (province.children) {
                        province.children.forEach(city => {
                            v3AreaState.selectedCities.delete(city.id);
                            if (city.children) {
                                city.children.forEach(district => {
                                    v3AreaState.selectedDistricts.delete(district.id);
                                });
                            }
                        });
                    }
                } else {
                    v3AreaState.selectedProvinces.add(province.id);
                }
            },

            toggleV3ProvinceExpansion: (province) => {
                if (v3AreaState.expandedProvinces.has(province.id)) {
                    // 如果当前省份已经展开，则关闭它
                    v3AreaState.expandedProvinces.delete(province.id);
                    // 同时关闭该省份下所有城市的展开状态
                    if (province.children) {
                        province.children.forEach(city => {
                            v3AreaState.expandedCities.delete(city.id);
                        });
                    }
                } else {
                    // 如果当前省份未展开，先关闭所有其他省份的展开状态
                    const allProvinces = areaTree.value || [];
                    allProvinces.forEach(otherProvince => {
                        if (otherProvince.id !== province.id) {
                            v3AreaState.expandedProvinces.delete(otherProvince.id);
                            // 同时关闭该省份下所有城市的展开状态
                            if (otherProvince.children) {
                                otherProvince.children.forEach(city => {
                                    v3AreaState.expandedCities.delete(city.id);
                                });
                            }
                        }
                    });
                    // 然后展开当前省份
                    v3AreaState.expandedProvinces.add(province.id);
                }
            },

            toggleV3CitySelection: (city, province) => {
                if (v3AreaState.selectedCities.has(city.id)) {
                    v3AreaState.selectedCities.delete(city.id);
                    // 取消选择城市时，同时取消下级所有选择
                    if (city.children) {
                        city.children.forEach(district => {
                            v3AreaState.selectedDistricts.delete(district.id);
                        });
                    }
                } else {
                    v3AreaState.selectedCities.add(city.id);
                }
            },

            toggleV3CityExpansion: (city) => {
                if (v3AreaState.expandedCities.has(city.id)) {
                    // 如果当前城市已经展开，则关闭它
                    v3AreaState.expandedCities.delete(city.id);
                } else {
                    // 如果当前城市未展开，先关闭所有其他城市的展开状态
                    const allProvinces = areaTree.value || [];
                    allProvinces.forEach(province => {
                        if (province.children) {
                            province.children.forEach(otherCity => {
                                if (otherCity.id !== city.id) {
                                    v3AreaState.expandedCities.delete(otherCity.id);
                                }
                            });
                        }
                    });
                    // 然后展开当前城市
                    v3AreaState.expandedCities.add(city.id);
                }
            },

            toggleV3DistrictSelection: (district, city, province) => {
                if (v3AreaState.selectedDistricts.has(district.id)) {
                    v3AreaState.selectedDistricts.delete(district.id);
                } else {
                    v3AreaState.selectedDistricts.add(district.id);
                }
            },

            toggleSelectAllV3Provinces: () => {
                const allSelected = areaTree.value.length > 0 &&
                       areaTree.value.every(province => v3AreaState.selectedProvinces.has(province.id));
                if (allSelected) {
                    v3AreaState.selectedProvinces.clear();
                    v3AreaState.selectedCities.clear();
                    v3AreaState.selectedDistricts.clear();
                } else {
                    areaTree.value.forEach(province => {
                        v3AreaState.selectedProvinces.add(province.id);
                    });
                }
            },

            toggleSelectAllV3Cities: () => {
                const expandedCities = [];
                areaTree.value.forEach(province => {
                    if (v3AreaState.expandedProvinces.has(province.id) && province.children) {
                        expandedCities.push(...province.children);
                    }
                });

                const allSelected = expandedCities.length > 0 &&
                       expandedCities.every(city => v3AreaState.selectedCities.has(city.id));

                if (allSelected) {
                    expandedCities.forEach(city => {
                        v3AreaState.selectedCities.delete(city.id);
                        if (city.children) {
                            city.children.forEach(district => {
                                v3AreaState.selectedDistricts.delete(district.id);
                            });
                        }
                    });
                } else {
                    expandedCities.forEach(city => {
                        v3AreaState.selectedCities.add(city.id);
                    });
                }
            },

            toggleSelectAllV3Districts: () => {
                const expandedDistricts = [];
                areaTree.value.forEach(province => {
                    if (province.children) {
                        province.children.forEach(city => {
                            if (v3AreaState.expandedCities.has(city.id) && city.children) {
                                expandedDistricts.push(...city.children);
                            }
                        });
                    }
                });

                const allSelected = expandedDistricts.length > 0 &&
                       expandedDistricts.every(district => v3AreaState.selectedDistricts.has(district.id));

                if (allSelected) {
                    expandedDistricts.forEach(district => {
                        v3AreaState.selectedDistricts.delete(district.id);
                    });
                } else {
                    expandedDistricts.forEach(district => {
                        v3AreaState.selectedDistricts.add(district.id);
                    });
                }
            },

            isAllV3ProvincesSelected: () => {
                return areaTree.value.length > 0 &&
                       areaTree.value.every(province => v3AreaState.selectedProvinces.has(province.id));
            },

            isAllV3CitiesSelected: () => {
                const expandedCities = [];
                areaTree.value.forEach(province => {
                    if (v3AreaState.expandedProvinces.has(province.id) && province.children) {
                        expandedCities.push(...province.children);
                    }
                });
                return expandedCities.length > 0 &&
                       expandedCities.every(city => v3AreaState.selectedCities.has(city.id));
            },

            isAllV3DistrictsSelected: () => {
                const expandedDistricts = [];
                areaTree.value.forEach(province => {
                    if (province.children) {
                        province.children.forEach(city => {
                            if (v3AreaState.expandedCities.has(city.id) && city.children) {
                                expandedDistricts.push(...city.children);
                            }
                        });
                    }
                });
                return expandedDistricts.length > 0 &&
                       expandedDistricts.every(district => v3AreaState.selectedDistricts.has(district.id));
            }
        };

        // 将需要暴露给模板的状态与方法从 setup 返回
        return {
            // 表单数据
            freightForm,
            strategyForm,
            areaForm,
            mappingForm,
            batchMappingForm,
            editMappingForm,
            weightRuleForm,
            assignmentForm,
            batchAssignmentForm,

            // 数据存储
            areas,
            strategies,
            mappings,
            weightRules,
            assignments,
            batchWeightRules,
            filteredAssignments,
            mappingMergedData,
            mappingGroupByAreaData,
            filteredWeightRules,

            // 显示模式状态
            displayMode,

            // 模态框控制
            showAddStrategyModal,
            showEditStrategyModal,
            showCopyStrategyModal,
            currentStrategyForCopy,
            copyStrategyForm,
            copyStrategyNewName,
            copyStrategyDescription,
            showAddAreaModal,
            showEditAreaModal,
            showAddMappingModal,
            showEditMappingModal,
            showBatchMappingModal,
            showAddWeightRuleModal,
            showEditWeightRuleModal,
            showAddAssignmentModal,
            showBatchAssignmentModal,

            // 策略编辑相关状态
            showMappingStrategyEditModal,
            submittingMappingStrategy,
            mappingStrategyForm,

            // V3策略配置相关状态
            v3CurrentStrategy,
            selectedStrategyId,
            selectedMappingStrategyId,

            // 方法
            getPricingModelName
        };
    }
};

// 创建应用并挂载
const app = Vue.createApp(FreightApp);
const appInstance = app.mount('#app');

// 导出应用配置和实例供外部使用
window.FreightApp = FreightApp;
window.vueAppInstance = appInstance;

console.log('🎉 运费快速计算系统整合版本已启动');
console.log('✅ 已解决模块化架构中的API初始化问题');
console.log('✅ 所有HTTP请求统一使用POST方法');
console.log('✅ 全局应用实例已注册，支持freight-calculation.js模块访问');

// ============================= 新增配置字段变化处理函数 =============================

/**
 * 取消暂存的地区配置
 * @param {string} tempId - 临时配置 ID
 */
window.cancelPendingAreaConfig = function(tempId) {
    console.log('🗑️ [取消] 取消暂存的地区配置, 临时ID:', tempId);

    if (!window.pendingNewAreaConfigs || !window.pendingNewAreaConfigs.has(tempId)) {
        console.warn('⚠️ 未找到指定的暂存配置:', tempId);
        showMessage('未找到指定的暂存配置', true);
        return;
    }

    // 获取配置名称用于显示
    const config = window.pendingNewAreaConfigs.get(tempId);
    const configName = config ? config.name : '未知配置';

    // 从暂存列表中移除
    window.pendingNewAreaConfigs.delete(tempId);
    console.log('✅ 已从暂存列表中移除配置:', configName);

    // 移除对应的DOM元素
    const pendingRow = document.querySelector(`tr[data-temp-id="${tempId}"], .pending-new-config input[data-temp-id="${tempId}"]`);
    if (pendingRow) {
        // 找到最近的tr元素
        const rowElement = pendingRow.closest('tr');
        if (rowElement) {
            rowElement.remove();
            console.log('✅ 已移除DOM元素');
        }
    } else {
        console.warn('⚠️ 未找到对应的DOM元素:', tempId);
    }

    // 显示成功消息
    showMessage(`已取消暂存的地区配置：${configName}`);

    // 重新排序和更新剩余暂存配置的名称下标
    if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.size > 0) {
        console.log('🔄 重新计算剩余暂存配置的名称下标...');

        // 获取已保存配置的最大下标
        const existingRows = document.querySelectorAll('#area-pricing-list tr[data-pricing-id]');
        let maxExistingIndex = 0;

        existingRows.forEach(row => {
            const nameInput = row.querySelector('input[data-field="name"]');
            if (nameInput && nameInput.value) {
                const match = nameInput.value.match(/配置名称-(\d+)$/);
                if (match) {
                    maxExistingIndex = Math.max(maxExistingIndex, parseInt(match[1]));
                }
            }
        });

        // 重新分配暂存配置的名称下标
        let nextIndex = maxExistingIndex + 1;
        window.pendingNewAreaConfigs.forEach((config, tempId) => {
            const newName = `配置名称-${nextIndex}`;
            config.name = newName;

            // 更新DOM中的显示
            const nameInput = document.querySelector(`input[data-temp-id="${tempId}"][data-field="name"]`);
            if (nameInput) {
                nameInput.value = newName;
            }

            console.log('✅ 重新设置暂存配置名称:', tempId, '->', newName);
            nextIndex++;
        });
    }

    // 检查是否需要显示空状态
    const areaPricingList = document.getElementById('area-pricing-list');
    if (areaPricingList) {
        const remainingRows = areaPricingList.querySelectorAll('tr[data-pricing-id], tr[data-temp-id]');
        if (remainingRows.length === 0) {
            // 没有任何配置，显示空状态
            areaPricingList.innerHTML = `
                <tr>
                    <td colspan="9" class="empty-cell">
                        <div class="empty-state">
                            <i class="icon-location"></i>
                            <p>暂无地区配置</p>
                            <p class="empty-hint">请点击上方“添加地区”按钮添加新的地区配置</p>
                        </div>
                    </td>
                </tr>
            `;
            console.log('📋 没有其他配置，已显示空状态');
        }
    }

    console.log('✅ [取消] 暂存配置取消完成');
};

/**
 * 处理待保存配置的名称变化
 */
window.handlePendingConfigNameChange = function(inputElement) {
    const tempId = inputElement.dataset.tempId;
    const newName = inputElement.value;

    if (!tempId || !newName.trim()) {
        return;
    }

    console.log('📝 新增配置名称变化:', { tempId, newName });

    // 标记为已修改
    inputElement.classList.add('modified');

    // 更新暂存配置数据
    if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.has(tempId)) {
        const config = window.pendingNewAreaConfigs.get(tempId);
        config.name = newName;
        console.log('✅ 暂存配置名称已更新:', { tempId, name: newName });
    }
};

/**
 * 处理待保存配置的其他字段变化
 */
window.handlePendingConfigFieldChange = function(inputElement) {
    const tempId = inputElement.dataset.tempId;
    const fieldName = inputElement.dataset.field;
    const newValue = inputElement.value;

    if (!tempId || !fieldName) {
        return;
    }

    console.log('📝 新增配置字段变化:', { tempId, fieldName, newValue });

    // 数值字段不立即验证，等待失去焦点时再处理
    if (['firstWeightKg', 'firstWeightFee', 'additionalWeightKg', 'additionalWeightFee', 'volumetricWeightRatio'].includes(fieldName)) {
        inputElement.classList.remove('error'); // 移除之前的错误样式
    }

    // 标记为已修改
    inputElement.classList.add('modified');

    // 更新暂存配置数据
    if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.has(tempId)) {
        const config = window.pendingNewAreaConfigs.get(tempId);

        // 根据字段类型处理数值
        if (['firstWeightKg', 'firstWeightFee', 'additionalWeightKg', 'additionalWeightFee', 'volumetricWeightRatio'].includes(fieldName)) {
            config[fieldName] = parseFloat(newValue) || 0;
        } else {
            config[fieldName] = newValue;
        }

        console.log('✅ 暂存配置字段已更新:', { tempId, fieldName, value: config[fieldName] });

        // 如果是重量或费用相关字段，自动更新描述
        if (['firstWeightKg', 'firstWeightFee', 'additionalWeightKg', 'additionalWeightFee', 'volumetricWeightRatio'].includes(fieldName)) {
            updatePendingConfigDescription(tempId);
        }
    }
};

/**
 * 处理数值输入框失去焦点时的验证
 */
window.handlePendingConfigFieldBlur = function(inputElement) {
    const tempId = inputElement.dataset.tempId;
    const fieldName = inputElement.dataset.field;
    const newValue = inputElement.value;

    if (!tempId || !fieldName) {
        return;
    }

    // 数值字段校验
    if (['firstWeightKg', 'firstWeightFee', 'additionalWeightKg', 'additionalWeightFee', 'volumetricWeightRatio'].includes(fieldName)) {
        const numValue = parseFloat(newValue);
        if (isNaN(numValue) || numValue < 0) {
            // 显示错误信息
            let fieldDisplayName = '';
            switch(fieldName) {
                case 'firstWeightKg': fieldDisplayName = '首重重量'; break;
                case 'firstWeightFee': fieldDisplayName = '首重费用'; break;
                case 'additionalWeightKg': fieldDisplayName = '续重重量'; break;
                case 'additionalWeightFee': fieldDisplayName = '续重费用'; break;
                case 'volumetricWeightRatio': fieldDisplayName = '抛重比'; break;
            }
            showMessage(`${fieldDisplayName}不能为负数，已自动重置为0`, 'warning');

            // 重置为默认值
            inputElement.value = '0';
            inputElement.classList.add('error');
            setTimeout(() => {
                inputElement.classList.remove('error');
            }, 2000);

            // 更新暂存配置数据
            if (window.pendingNewAreaConfigs && window.pendingNewAreaConfigs.has(tempId)) {
                const config = window.pendingNewAreaConfigs.get(tempId);
                config[fieldName] = 0;
                updatePendingConfigDescription(tempId);
            }
        }
    }
};

/**
 * 自动更新待保存配置的描述
 */
function updatePendingConfigDescription(tempId) {
    if (!window.pendingNewAreaConfigs || !window.pendingNewAreaConfigs.has(tempId)) {
        return;
    }

    const config = window.pendingNewAreaConfigs.get(tempId);
    const firstWeightKg = config.firstWeightKg !== undefined && config.firstWeightKg !== null ? config.firstWeightKg : 0;
    const firstWeightFee = config.firstWeightFee !== undefined && config.firstWeightFee !== null ? config.firstWeightFee : 0;
    const additionalWeightKg = config.additionalWeightKg !== undefined && config.additionalWeightKg !== null ? config.additionalWeightKg : 0;
    const additionalWeightFee = config.additionalWeightFee !== undefined && config.additionalWeightFee !== null ? config.additionalWeightFee : 0;
    const volumetricWeightRatio = config.volumetricWeightRatio !== undefined && config.volumetricWeightRatio !== null ? config.volumetricWeightRatio : 0;

    // 使用全局配置系统中的抛重比计算公式
    const displayRatio = window.FREIGHT_CONFIG ?
        window.FREIGHT_CONFIG.volumetricWeightRatioFormula.getDisplayRatio(volumetricWeightRatio) :
        volumetricWeightRatio > 0 ? (volumetricWeightRatio / 1000000 * 200).toFixed(1) : '0.0';

    const newDescription = `首重${firstWeightKg}kg/${firstWeightFee}元，续重${additionalWeightKg}kg/${additionalWeightFee}元，抛重比${displayRatio}`;
    config.description = newDescription;

    // 更新页面显示的描述输入框
    const descriptionInput = document.querySelector(`input[data-temp-id="${tempId}"][data-field="description"]`);
    if (descriptionInput) {
        descriptionInput.value = newDescription;
    }

    console.log('✅ 自动更新配置描述:', { tempId, description: newDescription });

    // 表单数据
    freightForm,
    strategyForm,
    areaForm,
    mappingForm,
    batchMappingForm,
    editMappingForm,
    weightRuleForm,
    assignmentForm,
    batchAssignmentForm,

    // 数据存储
    areas,
    strategies,
    mappings,
    weightRules,
    assignments,
    batchWeightRules,
    filteredAssignments,
    mappingMergedData,
    mappingGroupByAreaData,
    filteredWeightRules,

    // 显示模式状态
    displayMode,

    // 模态框控制
    showAddStrategyModal,
    showEditStrategyModal,
    showCopyStrategyModal,
    currentStrategyForCopy,
    copyStrategyForm,
    copyStrategyNewName,
    copyStrategyDescription,
    showAddAreaModal,
    showEditAreaModal,
    showAddMappingModal,
    showEditMappingModal,
    showBatchMappingModal,
    showAddWeightRuleModal,
    showEditWeightRuleModal,
    showAddAssignmentModal,
    showBatchAssignmentModal,

    // 策略编辑相关状态
    showMappingStrategyEditModal,
    submittingMappingStrategy,
    mappingStrategyForm,

    // 方法
    getPricingModelName
};
